public static bool IsNetworkUnavailableFrom(WebException e) { return IsNetworkApproximatelyUnavailable () || e.Status == WebExceptionStatus.NameResolutionFailure || e.Status == WebExceptionStatus.Timeout || e.Status == WebExceptionStatus.ConnectFailure; }
private string FetchJson(string url) { if (url == null || !url.Contains("http://")) { this.logger.Error("Invalid url: {0}", url); return string.Empty; } string jsonContent; using (var webClient = new System.Net.WebClient()) { webClient.Proxy = null; this.logger.Info("Downloading JSON from {0}", url); try { jsonContent = webClient.DownloadString(url); } catch (WebException e) { this.logger.Error("Failed to download {0}: {1}", url, e.Message); this.webException = e; return string.Empty; } } return jsonContent; }
private static object ReadResponseFromError(WebException error, int httpcode) { string temp; using (var streamReader = new StreamReader(error.Response.GetResponseStream())) temp = streamReader.ReadToEnd(); if (httpcode > 0) { switch (httpcode) { case 403: return 403; case 400: return 400; case 502: return 502; case 503: return 503; case 504: return 504; default: if (StripHtml(temp) == String.Empty) return httpcode; return httpcode; } } return string.Empty; }
/// <summary> /// Initializes a new instance. /// </summary> /// <param name="innerException"></param> public SDataException(WebException innerException) : base(innerException.Message, innerException, innerException.Status, innerException.Response) { if (Response == null) { return; } var httpResponse = Response as HttpWebResponse; _statusCode = httpResponse != null ? httpResponse.StatusCode : (HttpStatusCode?) null; MediaType mediaType; if (MediaTypeNames.TryGetMediaType(Response.ContentType, out mediaType) && mediaType == MediaType.Xml) { var serializer = new XmlSerializer(typeof (Diagnosis)); using (var stream = Response.GetResponseStream()) { try { _diagnosis = (Diagnosis) serializer.Deserialize(stream); } catch (XmlException) { } catch (InvalidOperationException) { } } } }
public static string SerializeWebException(WebException ex) { var dictionary = new Dictionary<string, string>(); dictionary["StatusCode"] = ((int)((HttpWebResponse)(ex.Response)).StatusCode).ToString(); Stream responseStream = ex.Response.GetResponseStream(); if (responseStream != null) { dictionary["Body"] = StreamToString(responseStream); responseStream.Position = 0; if (ex.Response.Headers.AllKeys.Contains("WWW-Authenticate", StringComparer.OrdinalIgnoreCase)) { dictionary["WWW-AuthenticateHeader"] = ex.Response.Headers["WWW-Authenticate"]; } } else { dictionary["Body"] = string.Empty; } using (Stream stream = new MemoryStream()) { SerializeDictionary(dictionary, stream); stream.Seek(0, SeekOrigin.Begin); return EncodingHelper.Base64Encode(StreamToString(stream)); } }
public void MediaRetryPolicyTestExecuteActionBackoff() { MediaRetryPolicy target = new TestMediaServicesClassFactory(null).GetSaveChangesRetryPolicy(); int exceptionCount = 5; int expected = 10; var fakeException = new WebException("test", WebExceptionStatus.ConnectionClosed); TimeSpan lastInterval = TimeSpan.Zero; DateTime lastInvoked = DateTime.UtcNow; Func<int> func = () => { TimeSpan newInterval = DateTime.UtcNow - lastInvoked; TimeSpan delta = newInterval - lastInterval; Assert.IsTrue(exceptionCount > 3 || delta.TotalMilliseconds > 1, "Iterations left:{0} interval increase too small from {1} to {2}", exceptionCount, lastInterval, newInterval, delta); lastInvoked = DateTime.UtcNow; lastInterval = newInterval; if (--exceptionCount > 0) throw fakeException; return expected; }; int actual = target.ExecuteAction(func); Assert.AreEqual(expected, actual); Assert.AreEqual(0, exceptionCount); }
public void MediaRetryPolicyTestExecuteActionNonTransient() { MediaRetryPolicy target = new TestMediaServicesClassFactory(null).GetSaveChangesRetryPolicy(); int exceptionCount = 2; int expected = 10; var fakeException = new WebException("test", WebExceptionStatus.RequestCanceled); Func<int> func = () => { if (--exceptionCount > 0) throw fakeException; return expected; }; try { target.ExecuteAction(func); } catch (WebException x) { Assert.AreEqual(1, exceptionCount); Assert.AreEqual(fakeException, x); throw; } Assert.Fail("Expected exception"); }
public static WebRequestException CreateFromWebException(WebException ex) { var response = ex.Response as HttpWebResponse; return response == null ? new WebRequestException(ex) : new WebRequestException(ex.Message, response, ex); }
public void GetOperationTest() { var data = new OperationData { Id = "1", State = OperationState.Succeeded.ToString() }; var dataContextMock = new Mock<IMediaDataServiceContext>(); var fakeException = new WebException("test", WebExceptionStatus.ConnectionClosed); var fakeResponse = new OperationData[] { data }; int exceptionCount = 2; dataContextMock.Setup((ctxt) => ctxt .Execute<OperationData>(It.IsAny<Uri>())) .Returns(() => { if (--exceptionCount > 0) throw fakeException; return fakeResponse; }); _mediaContext.MediaServicesClassFactory = new TestMediaServicesClassFactory(dataContextMock.Object); var actual = _mediaContext.Operations.GetOperation(data.Id); Assert.AreEqual(data.Id, actual.Id); dataContextMock.Verify((ctxt) => ctxt.Execute<OperationData>(It.IsAny<Uri>()), Times.Exactly(2)); }
private string GetResponse(string url, WebException exception) { var logMessage = new StringBuilder(); logMessage.AppendLine("********************************************************"); logMessage.AppendLine("Error loading url: " + url); logMessage.AppendLine(exception.Message); if (exception.Response != null) { try { var responseStream = exception.Response.GetResponseStream(); if (responseStream != null) { using (var reader = new StreamReader(responseStream)) { string responseText = reader.ReadToEnd(); logMessage.AppendLine(responseText); } } } catch (Exception) {} } return logMessage.ToString(); }
private static void HandleDownloadException(string url, WebException ex, Failed failed) { StringBuilder builder = new StringBuilder(); builder.AppendFormat("Failed to download '{0}'.", url); builder.Append("\r\n"); // do we have a response... if (ex.Response != null) { try { Stream stream = ex.Response.GetResponseStream(); if (stream == null) throw new InvalidOperationException("'stream' is null."); using (stream) { builder.Append("Response data: "); // reader... using (StreamReader reader = new StreamReader(stream)) builder.Append(reader.ReadToEnd()); } } catch (Exception readEx) { builder.AppendFormat("An exception occurred when reading error data: " + readEx.Message); } } else builder.Append("(No response)"); // defer to the context... failed(new InvalidOperationException(builder.ToString(), ex)); }
void DisplayWebException( WebException ex, string action ) { ErrorHandler.LogError( action, ex ); if( ex.Status == WebExceptionStatus.Timeout ) { string text = "&eFailed to " + action + ":" + Environment.NewLine + "Timed out while connecting to classicube.net."; SetStatus( text ); } else if( ex.Status == WebExceptionStatus.ProtocolError ) { HttpWebResponse response = (HttpWebResponse)ex.Response; int errorCode = (int)response.StatusCode; string description = response.StatusDescription; string text = "&eFailed to " + action + ":" + Environment.NewLine + " classicube.net returned: (" + errorCode + ") " + description; SetStatus(text ); } else if( ex.Status == WebExceptionStatus.NameResolutionFailure ) { string text = "&eFailed to " + action + ":" + Environment.NewLine + "Unable to resolve classicube.net" + Environment.NewLine + "you may not be connected to the internet."; SetStatus( text ); } else { string text = "&eFailed to " + action + ":" + Environment.NewLine + ex.Status; SetStatus( text ); } }
private WebException GetWebException(Stream responseStream ) { var webResponse = Substitute.For<HttpWebResponse>(); webResponse.GetResponseStream().Returns(responseStream); var wex = new WebException("test", null, WebExceptionStatus.UnknownError, webResponse); return wex; }
public void TestNotificationEndPointCreateFailedRetryMessageLengthLimitExceeded() { var expected = new NotificationEndPoint { Name = "testData" }; var fakeException = new WebException("test", WebExceptionStatus.MessageLengthLimitExceeded); var dataContextMock = TestMediaServicesClassFactory.CreateSaveChangesMock(fakeException, 10, expected); dataContextMock.Setup((ctxt) => ctxt.AddObject("NotificationEndPoints", It.IsAny<object>())); _mediaContext.MediaServicesClassFactory = new TestMediaServicesClassFactory(dataContextMock.Object); try { _mediaContext.NotificationEndPoints.Create("Empty", NotificationEndPointType.AzureQueue, "127.0.0.1"); } catch (WebException x) { dataContextMock.Verify((ctxt) => ctxt.SaveChangesAsync(It.IsAny<object>()), Times.Exactly(1)); Assert.AreEqual(fakeException, x); throw; } Assert.Fail("Expected exception"); }
public IAuthenticator Next(WebException ex) { // No user name provided, just throw if (string.IsNullOrEmpty(_user)) return null; var response = (HttpWebResponse)ex.Response; var header = response.Headers["WWW-Authenticate"]; if (response.StatusCode != HttpStatusCode.Unauthorized || string.IsNullOrEmpty(header)) return null; if (header.StartsWith("Digest ", StringComparison.InvariantCultureIgnoreCase)) { var digest = new DigestToken(header, _user, _password); return new DigestAuthenticator(digest); } // Probably bad username/password return null; }
/// <summary> /// Creates a new Eve Crest Exception /// </summary> /// <param name="message">Error message returned by CREST</param> /// <param name="innerException">The WebException that caused this exception</param> /// <param name="key">The Key returned by CREST</param> /// <param name="exceptionType">The Exception Type returned by CREST</param> /// <param name="refId">the Ref ID returned by CREST</param> public EveCrestException(string message, WebException innerException, string key, string exceptionType, string refId) : base(message, innerException) { Key = key; ExceptionType = exceptionType; RefId = refId; }
public void TestChannelCreateRetry() { var expected = new ChannelData { Name = "testData" }; var fakeException = new WebException("test", WebExceptionStatus.ConnectionClosed); var dataContextMock = TestMediaServicesClassFactory.CreateSaveChangesMock(fakeException, 2, expected); dataContextMock.Setup(ctxt => ctxt.AddObject("Channels", It.IsAny<object>())); _mediaContext.MediaServicesClassFactory = new TestMediaServicesClassFactory(dataContextMock.Object); try { _mediaContext.Channels.Create( new ChannelCreationOptions { Name = "unittest", Input = MakeChannelInput(), Preview = MakeChannelPreview(), Output = MakeChannelOutput() }); } catch (NotImplementedException x) { Assert.AreEqual(TestMediaDataServiceResponse.TestMediaDataServiceResponseExceptionMessage, x.Message); } dataContextMock.Verify(ctxt => ctxt.SaveChangesAsync(It.IsAny<object>()), Times.Exactly(2)); }
static string GetErrorMessage(WebException ex) { var r = ex.Response as HttpWebResponse; return r == null ? ex.Message : $"{r.StatusCode:d} - {r.Headers["x-error-message"]}"; }
public void TestChannelCreateFailedRetry() { var expected = new ChannelData { Name = "testData" }; var fakeException = new WebException("test", WebExceptionStatus.ConnectionClosed); var dataContextMock = TestMediaServicesClassFactory.CreateSaveChangesMock(fakeException, 10, expected); dataContextMock.Setup(ctxt => ctxt.AddObject("Channels", It.IsAny<object>())); _mediaContext.MediaServicesClassFactory = new TestMediaServicesClassFactory(dataContextMock.Object); try { _mediaContext.Channels.Create( new ChannelCreationOptions { Name = "unittest", Input = MakeChannelInput(), Preview = MakeChannelPreview(), Output = MakeChannelOutput() }); } catch (WebException x) { dataContextMock.Verify(ctxt => ctxt.SaveChangesAsync(It.IsAny<object>()), Times.AtLeast(3)); Assert.AreEqual(fakeException, x); throw; } Assert.Fail("Expected exception"); }
private static void HandleConnection(WebException ex) { Log.Error(ex); StatusNotification.Notify("Connection failed"); if (ex.Status == WebExceptionStatus.NameResolutionFailure) { MessageBox.Show("Could not find the server. Please check the URL.", "Connection failed", MessageBoxButton.OK, MessageBoxImage.Information); } else if ( ex.Response is HttpWebResponse) { var response = (HttpWebResponse)ex.Response; switch (response.StatusCode) { case HttpStatusCode.BadGateway: MessageBox.Show("Could not find the server. Please check the URL.", "Connection failed", MessageBoxButton.OK, MessageBoxImage.Information); break; case HttpStatusCode.Unauthorized: case HttpStatusCode.Forbidden: MessageBox.Show("You are not authorized to open this site", "Connection failed", MessageBoxButton.OK, MessageBoxImage.Information); break; default: MessageBox.Show(ex.Message, "Connection failed", MessageBoxButton.OK, MessageBoxImage.Information); break; } } else MessageBox.Show(ex.ToString(), "Connection failed", MessageBoxButton.OK, MessageBoxImage.Information); }
public static TaskCompletedSummary GetSummaryFromWebException(string taskName, WebException e) { var webResponse = e.Response as HttpWebResponse; if (webResponse != null && webResponse.StatusCode == HttpStatusCode.Unauthorized) { //// "Access denied // check credentials" return new TaskCompletedSummary { Task = taskName, Result = TaskSummaryResult.AccessDenied }; } string response; using (var stream = e.Response.GetResponseStream()) { var buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); response = System.Text.Encoding.UTF8.GetString(buffer, 0, buffer.Length); } if (string.IsNullOrEmpty(response)) { //// "Can not connect to server // check conectivity"; return new TaskCompletedSummary { Task = taskName, Result = TaskSummaryResult.UnreachableServer }; } return new TaskCompletedSummary { Task = taskName, Result = TaskSummaryResult.UnknownError }; }
private string extractErrorDetails(WebException ex) { string responseBody = ""; using (WebResponse response = ex.Response) { HttpWebResponse httpResponse = (HttpWebResponse)response; if (httpResponse != null) { responseStatusCode = httpResponse.StatusCode; if (httpResponse.StatusCode == HttpStatusCode.BadRequest) { using (Stream data = response.GetResponseStream()) using (var reader = new StreamReader(data)) { responseBody = reader.ReadToEnd(); } } } if (responseBody == "") { responseBody = "{\"Exception\":\"" + ex.Message + "\"}"; } } return responseBody; }
private static FeedVerificationResult HandleWebException(WebException exception, string source) { try { var httpWebResponse = (HttpWebResponse)exception.Response; if (ReferenceEquals(httpWebResponse, null)) { return FeedVerificationResult.Invalid; } if ((int)httpWebResponse.StatusCode == 403) { return FeedVerificationResult.Valid; } if (exception.Status == WebExceptionStatus.ProtocolError) { return httpWebResponse.StatusCode == HttpStatusCode.Unauthorized ? FeedVerificationResult.AuthenticationRequired : FeedVerificationResult.Invalid; } } catch (Exception ex) { Log.Debug(ex, "Failed to verify feed '{0}'", source); } return FeedVerificationResult.Invalid; }
public void ContentKeyBaseCollectionGetProtectionKeyIdForContentKeyRetry() { var dataContextMock = new Mock<IMediaDataServiceContext>(); var fakeException = new WebException("test", WebExceptionStatus.ConnectionClosed); var fakeResponse = new string[] { "testKey" }; int exceptionCount = 2; dataContextMock.Setup((ctxt) => ctxt .Execute<string>(It.IsAny<Uri>())) .Returns(() => { if (--exceptionCount > 0) throw fakeException; return fakeResponse; }); _mediaContext.MediaServicesClassFactory = new TestMediaServicesClassFactory(dataContextMock.Object); var actual = ContentKeyBaseCollection.GetProtectionKeyIdForContentKey(_mediaContext, ContentKeyType.CommonEncryption); Assert.AreEqual(fakeResponse[0], actual); dataContextMock.Verify((ctxt) => ctxt.Execute<string>(It.IsAny<Uri>()), Times.Exactly(2)); }
public void UploadData(byte[] data) { try { //this.m_Method = method;//this sets someone else request.ContentLength = data.Length;//this is my responsability to set this.UploadBits( request.GetRequestStream(), null,data, null, null); //buffer2 = this.DownloadBits(request, null, null, null); } catch (Exception exception) { if (((exception is ThreadAbortException) || (exception is StackOverflowException)) || (exception is OutOfMemoryException)) { throw; } if (!(exception is WebException) && !(exception is SecurityException)) { exception = new WebException("Curl", exception); } AbortRequest(); throw exception; } }
public void TestSendDeleteOperationRetry() { var data = new StreamingEndpointData { Name = "testData", Id = "1" }; var fakeException = new WebException("test", WebExceptionStatus.ConnectionClosed); var dataContextMock = TestMediaServicesClassFactory.CreateSaveChangesMock(fakeException, 2, data); dataContextMock.Setup((ctxt) => ctxt.AttachTo("StreamingEndpoints", data)); dataContextMock.Setup((ctxt) => ctxt.DeleteObject(data)); _mediaContext.MediaServicesClassFactory = new TestMediaServicesClassFactory(dataContextMock.Object); data.SetMediaContext(_mediaContext); try { data.SendDeleteOperation(); } catch (NotImplementedException x) { Assert.AreEqual(TestMediaDataServiceResponse.TestMediaDataServiceResponseExceptionMessage, x.Message); } dataContextMock.Verify((ctxt) => ctxt.SaveChanges(), Times.Exactly(2)); }
private void AppendHttpResponseDetails(StringBuilder stringBuilder, WebException exception) { var httpWebResponse = exception.Response as HttpWebResponse; if (httpWebResponse == null) return; try { stringBuilder.AppendFormat ("StatusCode: {0}", httpWebResponse.StatusCode); stringBuilder.AppendLine(); stringBuilder.AppendFormat ("StatusDescription: {0}", httpWebResponse.StatusDescription); stringBuilder.AppendLine(); try { using (var reader = new StreamReader (httpWebResponse.GetResponseStream())) { stringBuilder.AppendFormat ("Body: {0}", reader.ReadToEnd()); stringBuilder.AppendLine(); } } catch (ProtocolViolationException) { // Occurs if there is no response stream and can be ignored } } catch (Exception x) { s_logger.Error ("Exception while getting exception details.", x); } }
internal static void ThrowSharpBoxExceptionBasedOnNetworkErrorCode(WebRequest uploadRequest, int code, WebException e) { if (Convert.ToInt32(code) == 507) throw new SharpBoxException(SharpBoxErrorCodes.ErrorInsufficientDiskSpace, e, uploadRequest, null); else throw new SharpBoxException(SharpBoxErrorCodes.ErrorCreateOperationFailed, e, uploadRequest, null); }
private static void TryHandleWebException(WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null) { var webResponse = (HttpWebResponse) ex.Response; if (webResponse == null) { return; } switch (webResponse.StatusCode) { case HttpStatusCode.Unauthorized: throw new MixPanelUnauthorizedException(); case HttpStatusCode.BadRequest: var responseStream = webResponse.GetResponseStream(); if (responseStream == null) return; var responseReader = new StreamReader(responseStream); var response = responseReader.ReadToEnd(); if (response.Contains("Unable to authenticate")) //some magic throw new MixPanelUnauthorizedException(); break; } } }
/// <summary> /// Common logic for handling web exceptions when connecting to the SonarQube server. Common exceptions /// are handled by logging user friendly errors. /// </summary> /// <returns>True if the exception was handled</returns> public static bool HandleHostUrlWebException(WebException ex, string hostUrl, ILogger logger) { var response = ex.Response as HttpWebResponse; if (response != null && response.StatusCode == HttpStatusCode.NotFound) { logger.LogError(Resources.ERROR_FileNotFound, response.ResponseUri); return true; } if (ex.Status == WebExceptionStatus.NameResolutionFailure) { logger.LogError(Resources.ERROR_UrlNameResolutionFailed, hostUrl); return true; } if (ex.Status == WebExceptionStatus.ConnectFailure) { logger.LogError(Resources.ERROR_ConnectionFailed, hostUrl); return true; } if (ex.Status == WebExceptionStatus.TrustFailure) { logger.LogError(Resources.ERROR_TrustFailure, hostUrl); return true; } return false; }
void ICloseEx.CloseEx(CloseExState closeState) { if (GlobalLog.IsEnabled) { GlobalLog.Print("FtpDataStream#" + LoggingHash.HashString(this) + "::CloseEx, state = " + closeState.ToString()); } lock (this) { if (_closing == true) { return; } _closing = true; _writeable = false; _readable = false; } try { try { if ((closeState & CloseExState.Abort) == 0) { _networkStream.Close(DefaultCloseTimeout); } else { _networkStream.Close(0); } } finally { _request.DataStreamClosed(closeState); } } catch (Exception exception) { bool doThrow = true; WebException webException = exception as WebException; if (webException != null) { FtpWebResponse response = webException.Response as FtpWebResponse; if (response != null) { if (!_isFullyRead && response.StatusCode == FtpStatusCode.ConnectionClosed) { doThrow = false; } } } if (doThrow) { if ((closeState & CloseExState.Silent) == 0) { throw; } } } }
private static void ThrowProtocolViolation(string message) { WebException ex = new WebException(message, null, WebExceptionStatus.ServerProtocolViolation, null); throw ex; }
private async Task BindAsmResources(AzureContext azureContext, TargetSettings targetSettings) { treeAzureASM.Nodes.Clear(); try { if (_AzureContextSource != null && _AzureContextSource.AzureSubscription != null) { await _AzureContextSource.AzureSubscription.BindAsmResources(targetSettings); if (_AzureContextSource != null && _AzureContextSource.AzureSubscription != null) { TreeNode subscriptionNodeASM = new TreeNode(_AzureContextSource.AzureSubscription.Name); treeAzureASM.Nodes.Add(subscriptionNodeASM); subscriptionNodeASM.Expand(); foreach (Azure.MigrationTarget.NetworkSecurityGroup targetNetworkSecurityGroup in _AzureContextSource.AzureSubscription.AsmTargetNetworkSecurityGroups) { Azure.Asm.NetworkSecurityGroup asmNetworkSecurityGroup = (Azure.Asm.NetworkSecurityGroup)targetNetworkSecurityGroup.SourceNetworkSecurityGroup; TreeNode parentNode = GetDataCenterTreeViewNode(subscriptionNodeASM, asmNetworkSecurityGroup.Location, "Network Security Groups"); TreeNode tnNetworkSecurityGroup = new TreeNode(targetNetworkSecurityGroup.SourceName); tnNetworkSecurityGroup.Name = targetNetworkSecurityGroup.SourceName; tnNetworkSecurityGroup.Tag = targetNetworkSecurityGroup; parentNode.Nodes.Add(tnNetworkSecurityGroup); parentNode.Expand(); } foreach (Azure.MigrationTarget.VirtualNetwork targetVirtualNetwork in _AzureContextSource.AzureSubscription.AsmTargetVirtualNetworks) { Azure.Asm.VirtualNetwork asmVirtualNetwork = (Azure.Asm.VirtualNetwork)targetVirtualNetwork.SourceVirtualNetwork; TreeNode parentNode = GetDataCenterTreeViewNode(subscriptionNodeASM, asmVirtualNetwork.Location, "Virtual Networks"); TreeNode tnVirtualNetwork = new TreeNode(targetVirtualNetwork.SourceName); tnVirtualNetwork.Name = targetVirtualNetwork.SourceName; tnVirtualNetwork.Text = targetVirtualNetwork.SourceName; tnVirtualNetwork.Tag = targetVirtualNetwork; parentNode.Nodes.Add(tnVirtualNetwork); parentNode.Expand(); } foreach (Azure.MigrationTarget.StorageAccount targetStorageAccount in _AzureContextSource.AzureSubscription.AsmTargetStorageAccounts) { TreeNode parentNode = GetDataCenterTreeViewNode(subscriptionNodeASM, targetStorageAccount.SourceAccount.PrimaryLocation, "Storage Accounts"); TreeNode tnStorageAccount = new TreeNode(targetStorageAccount.SourceName); tnStorageAccount.Name = targetStorageAccount.SourceName; tnStorageAccount.Tag = targetStorageAccount; parentNode.Nodes.Add(tnStorageAccount); parentNode.Expand(); } foreach (Azure.MigrationTarget.VirtualMachine targetVirtualMachine in _AzureContextSource.AzureSubscription.AsmTargetVirtualMachines) { Azure.Asm.VirtualMachine asmVirtualMachine = (Azure.Asm.VirtualMachine)targetVirtualMachine.Source; TreeNode parentNode = GetDataCenterTreeViewNode(subscriptionNodeASM, asmVirtualMachine.Location, "Cloud Services"); TreeNode[] cloudServiceNodeSearch = parentNode.Nodes.Find(targetVirtualMachine.TargetAvailabilitySet.TargetName, false); TreeNode cloudServiceNode = null; if (cloudServiceNodeSearch.Count() == 1) { cloudServiceNode = cloudServiceNodeSearch[0]; } cloudServiceNode = new TreeNode(targetVirtualMachine.TargetAvailabilitySet.TargetName); cloudServiceNode.Name = targetVirtualMachine.TargetAvailabilitySet.TargetName; cloudServiceNode.Tag = targetVirtualMachine.TargetAvailabilitySet; parentNode.Nodes.Add(cloudServiceNode); parentNode.Expand(); TreeNode virtualMachineNode = new TreeNode(targetVirtualMachine.SourceName); virtualMachineNode.Name = targetVirtualMachine.SourceName; virtualMachineNode.Tag = targetVirtualMachine; cloudServiceNode.Nodes.Add(virtualMachineNode); cloudServiceNode.Expand(); foreach (Azure.MigrationTarget.NetworkInterface targetNetworkInterface in targetVirtualMachine.NetworkInterfaces) { if (targetNetworkInterface.BackEndAddressPool != null && targetNetworkInterface.BackEndAddressPool.LoadBalancer != null) { TreeNode loadBalancerNode = new TreeNode(targetNetworkInterface.BackEndAddressPool.LoadBalancer.SourceName); loadBalancerNode.Name = targetNetworkInterface.BackEndAddressPool.LoadBalancer.SourceName; loadBalancerNode.Tag = targetNetworkInterface.BackEndAddressPool.LoadBalancer; cloudServiceNode.Nodes.Add(loadBalancerNode); cloudServiceNode.Expand(); foreach (Azure.MigrationTarget.FrontEndIpConfiguration frontEnd in targetNetworkInterface.BackEndAddressPool.LoadBalancer.FrontEndIpConfigurations) { if (frontEnd.PublicIp != null) // if external load balancer { TreeNode publicIPAddressNode = new TreeNode(frontEnd.PublicIp.SourceName); publicIPAddressNode.Name = frontEnd.PublicIp.SourceName; publicIPAddressNode.Tag = frontEnd.PublicIp; cloudServiceNode.Nodes.Add(publicIPAddressNode); cloudServiceNode.Expand(); } } } } } subscriptionNodeASM.Expand(); treeAzureASM.Enabled = true; } } } catch (Exception exc) { if (exc.GetType() == typeof(System.Net.WebException)) { System.Net.WebException webException = (System.Net.WebException)exc; if (webException.Response != null) { HttpWebResponse exceptionResponse = (HttpWebResponse)webException.Response; if (exceptionResponse.StatusCode == HttpStatusCode.Forbidden) { ASM403ForbiddenExceptionDialog forbiddenDialog = new ASM403ForbiddenExceptionDialog(_AzureContextSource.LogProvider, exc); return; } } } UnhandledExceptionDialog exceptionDialog = new UnhandledExceptionDialog(_AzureContextSource.LogProvider, exc); exceptionDialog.ShowDialog(); } _AzureContextSource.StatusProvider.UpdateStatus("Ready"); }
//TODO: Add this to FxCopBaseline.cs once https://github.com/dotnet/roslyn/issues/15728 is fixed void ICloseEx.CloseEx(CloseExState closeState) { if (NetEventSource.IsEnabled) { NetEventSource.Info(this, $"state = {closeState}"); } lock (this) { if (_closing == true) { return; } _closing = true; _writeable = false; _readable = false; } try { try { if ((closeState & CloseExState.Abort) == 0) { _networkStream.Close(DefaultCloseTimeout); } else { _networkStream.Close(0); } } finally { _request.DataStreamClosed(closeState); } } catch (Exception exception) { bool doThrow = true; WebException webException = exception as WebException; if (webException != null) { FtpWebResponse response = webException.Response as FtpWebResponse; if (response != null) { if (!_isFullyRead && response.StatusCode == FtpStatusCode.ConnectionClosed) { doThrow = false; } } } if (doThrow) { if ((closeState & CloseExState.Silent) == 0) { throw; } } } }
static private void ParseException(Exception ex, ref Exception result) { if (ex.GetType() == typeof(CookComputing.XmlRpc.XmlRpcFaultException)) { CookComputing.XmlRpc.XmlRpcFaultException xfe = (CookComputing.XmlRpc.XmlRpcFaultException)ex; if (xfe.FaultString.IndexOf("repeated requests") > -1) { result = new ExpectedSyncException(ExpectedError.RepeatedRequests, ex); } else if (xfe.FaultString.IndexOf("Cannot display this post") > -1) { result = new ExpectedSyncException(ExpectedError.NoEncodingSettings, ex); } else if (xfe.FaultString.IndexOf("Invalid password") > -1) { result = new ExpectedSyncException(ExpectedError.InvalidPassword, ex); } else if (xfe.FaultString.IndexOf("Unknown method") > -1) { result = new ExpectedSyncException(ExpectedError.ExportCommentsNotSupported, ex); } } else if (ex.GetType() == typeof(CookComputing.XmlRpc.XmlRpcServerException)) { CookComputing.XmlRpc.XmlRpcServerException xse = (CookComputing.XmlRpc.XmlRpcServerException)ex; if (xse.Message.ToLower().IndexOf("not found") > -1 || xse.Message.ToLower().IndexOf("not implemented") > -1 || xse.Message.ToLower().IndexOf("not modified") > -1) { result = new ExpectedSyncException(ExpectedError.XMLRPCNotSupported, ex); } else { result = new ExpectedSyncException(ExpectedError.ServerNotResponding, ex); } } else if (ex.GetType() == typeof(ThreadAbortException)) { result = new ExpectedSyncException(ExpectedError.Cancel, ex); } else if (ex.GetType() == typeof(System.Net.WebException)) { System.Net.WebException wex = (System.Net.WebException)ex; if (wex.Status == System.Net.WebExceptionStatus.ProtocolError) { result = new ExpectedSyncException(ExpectedError.ExportCommentsNotSupported, ex); } else { result = new ExpectedSyncException(ExpectedError.ServerNotResponding, ex); } } else if (ex.GetType() == typeof(CookComputing.XmlRpc.XmlRpcIllFormedXmlException)) { result = new ExpectedSyncException(ExpectedError.ServerNotResponding, ex); } if (result == null) { result = ex; } }
// If abortState becomes non-zero, the attempt to find a service point has been aborted. internal static ServicePoint FindServicePoint(Uri address, IWebProxy proxy, out ProxyChain chain, ref HttpAbortDelegate abortDelegate, ref int abortState) { if (address == null) { throw new ArgumentNullException("address"); } GlobalLog.Enter("ServicePointManager::FindServicePoint() address:" + address.ToString()); bool isProxyServicePoint = false; chain = null; // // find proxy info, and then switch on proxy // Uri proxyAddress = null; if (proxy != null && !address.IsLoopback) { IAutoWebProxy autoProxy = proxy as IAutoWebProxy; if (autoProxy != null) { chain = autoProxy.GetProxies(address); // Set up our ability to abort this MoveNext call. Note that the current implementations of ProxyChain will only // take time on the first call, so this is the only place we do this. If a new ProxyChain takes time in later // calls, this logic should be copied to other places MoveNext is called. GlobalLog.Assert(abortDelegate == null, "ServicePointManager::FindServicePoint()|AbortDelegate already set."); abortDelegate = chain.HttpAbortDelegate; try { Thread.MemoryBarrier(); if (abortState != 0) { Exception exception = new WebException(NetRes.GetWebStatusString(WebExceptionStatus.RequestCanceled), WebExceptionStatus.RequestCanceled); GlobalLog.LeaveException("ServicePointManager::FindServicePoint() Request aborted before proxy lookup.", exception); throw exception; } if (!chain.Enumerator.MoveNext()) { GlobalLog.Assert("ServicePointManager::FindServicePoint()|GetProxies() returned zero proxies."); /* * Exception exception = new WebException(NetRes.GetWebStatusString(WebExceptionStatus.RequestProhibitedByProxy), WebExceptionStatus.RequestProhibitedByProxy); * GlobalLog.LeaveException("ServicePointManager::FindServicePoint() Proxy prevented request.", exception); * throw exception; */ } proxyAddress = chain.Enumerator.Current; } finally { abortDelegate = null; } } else if (!proxy.IsBypassed(address)) { // use proxy support // rework address proxyAddress = proxy.GetProxy(address); } // null means DIRECT if (proxyAddress != null) { address = proxyAddress; isProxyServicePoint = true; } } ServicePoint servicePoint = FindServicePointHelper(address, isProxyServicePoint); GlobalLog.Leave("ServicePointManager::FindServicePoint() servicePoint#" + ValidationHelper.HashString(servicePoint)); return(servicePoint); }
internal static ContentstackException GetContentstackError(Exception ex) { Int32 errorCode = 0; string errorMessage = string.Empty; HttpStatusCode statusCode = HttpStatusCode.InternalServerError; ContentstackException contentstackError = new ContentstackException(ex); Dictionary <string, object> errors = null; //ContentstackError.OtherErrors errors = null; try { System.Net.WebException webEx = (System.Net.WebException)ex; using (var exResp = webEx.Response) using (var stream = exResp.GetResponseStream()) using (var reader = new StreamReader(stream)) { errorMessage = reader.ReadToEnd(); JObject data = JObject.Parse(errorMessage.Replace("\r\n", "")); //errorCode = ContentstackConvert.ToInt32(data.Property("error_code").Value); //errorMessage = ContentstackConvert.ToString(data.Property("error_message").Value); JToken token = data["error_code"]; if (token != null) { errorCode = token.Value <int>(); } token = data["error_message"]; if (token != null) { errorMessage = token.Value <string>(); } token = data["errors"]; if (token != null) { errors = token.ToObject <Dictionary <string, object> >(); } var response = exResp as HttpWebResponse; if (response != null) { statusCode = response.StatusCode; } } } catch { errorMessage = ex.Message; } contentstackError = new ContentstackException() { ErrorCode = errorCode, ErrorMessage = errorMessage, StatusCode = statusCode, Errors = errors }; return(contentstackError); }
public ProcessingErrorException(string message, System.Net.WebException e) : base(message, e) { }
private bool PostReadCommandProcessing(ref Stream stream) { if (_index >= _commands.Length) { return(false); } // Set up front to prevent a race condition on result == PipelineInstruction.Pause _doSend = false; _doRead = false; PipelineInstruction result; PipelineEntry entry; if (_index == -1) { entry = null; } else { entry = _commands[_index]; } // Final QUIT command may get exceptions since the connection // may be already closed by the server. So there is no response // to process, just advance the pipeline to continue. if (_currentResponseDescription == null && entry.Command == "QUIT\r\n") { result = PipelineInstruction.Advance; } else { result = PipelineCallback(entry, _currentResponseDescription, false, ref stream); } if (result == PipelineInstruction.Abort) { Exception exception; if (_abortReason != string.Empty) { exception = new WebException(_abortReason); } else { exception = GenerateException(SR.net_ftp_protocolerror, WebExceptionStatus.ServerProtocolViolation, null); } Abort(exception); throw exception; } else if (result == PipelineInstruction.Advance) { _currentResponseDescription = null; _doSend = true; _doRead = true; _index++; } else if (result == PipelineInstruction.Pause) { // PipelineCallback did an async operation and will have to re-enter again. // Hold on for now. return(true); } else if (result == PipelineInstruction.GiveStream) { // We will have another response coming, don't send _currentResponseDescription = null; _doRead = true; if (_isAsync) { // If they block in the requestcallback we should still continue the pipeline ContinueCommandPipeline(); InvokeRequestCallback(stream); } return(true); } else if (result == PipelineInstruction.Reread) { // Another response is expected after this one _currentResponseDescription = null; _doRead = true; } return(false); }
static void ThrowProtocolViolation(string message) { WebException we = new WebException(message, null, WebExceptionStatus.ServerProtocolViolation, null); throw we; }
private Result ErrorResult(System.Net.WebException e, string aChannel) { string descResult = aChannel + " - "; int codeResult = (int)e.Status; string aShortDescResult = aChannel + " - "; switch (e.Status) { //1 case WebExceptionStatus.NameResolutionFailure: descResult += "The name resolver service could not resolve the host name."; aShortDescResult += e.Status.ToString(); break; //2 case WebExceptionStatus.ConnectFailure: descResult += "The remote service point could not be contacted at the transport level."; aShortDescResult += e.Status.ToString(); break; //3 case WebExceptionStatus.ReceiveFailure: descResult += "A complete response was not received from the remote server."; aShortDescResult += e.Status.ToString(); break; //4 case WebExceptionStatus.SendFailure: descResult += "A complete request could not be sent to the remote server."; aShortDescResult += e.Status.ToString(); break; //5 case WebExceptionStatus.PipelineFailure: descResult += "The request was a pipelined request and the connection was " + "closed before the response was received."; aShortDescResult += e.Status.ToString(); break; //6 case WebExceptionStatus.RequestCanceled: descResult += "The request was canceled."; aShortDescResult += e.Status.ToString(); break; //7 case WebExceptionStatus.ProtocolError: HttpWebResponse resp = (HttpWebResponse)e.Response; codeResult = (int)resp.StatusCode; string[] arrDesc = this.DescProtocolError(resp); descResult += arrDesc[0]; aShortDescResult += arrDesc[1]; break; //8 case WebExceptionStatus.ConnectionClosed: descResult += "The connection was prematurely closed."; aShortDescResult += e.Status.ToString(); break; //9 case WebExceptionStatus.TrustFailure: descResult += "A server certificate could not be validated."; aShortDescResult += e.Status.ToString(); break; //10 case WebExceptionStatus.SecureChannelFailure: descResult += "An error occurred while establishing a connection using SSL."; aShortDescResult += e.Status.ToString(); break; //11 case WebExceptionStatus.ServerProtocolViolation: descResult += "The server response was not a valid HTTP response."; aShortDescResult += e.Status.ToString(); break; //12 case WebExceptionStatus.KeepAliveFailure: descResult += "The connection for a request that specifies the Keep-alive header " + "was closed unexpectedly."; aShortDescResult += e.Status.ToString(); break; //13 case WebExceptionStatus.Pending: descResult += "An internal asynchronous request is pending."; aShortDescResult += e.Status.ToString(); break; //14 case WebExceptionStatus.Timeout: descResult += "No response was received during the time-out period for a request."; aShortDescResult += e.Status.ToString(); break; //15 case WebExceptionStatus.ProxyNameResolutionFailure: descResult += "The name resolver service could not resolve the proxy host name."; aShortDescResult += e.Status.ToString(); break; //16 case WebExceptionStatus.UnknownError: descResult += "An exception of unknown type has occurred."; aShortDescResult += e.Status.ToString(); break; //17 case WebExceptionStatus.MessageLengthLimitExceeded: descResult += "A message was received that exceeded the specified limit when sending" + " a request or receiving a response from the server."; aShortDescResult += e.Status.ToString(); break; //18 case WebExceptionStatus.CacheEntryNotFound: descResult += "The specified cache entry was not found."; aShortDescResult += e.Status.ToString(); break; //19 case WebExceptionStatus.RequestProhibitedByCachePolicy: descResult += "The request was not permitted by the cache policy."; aShortDescResult += e.Status.ToString(); break; //20 case WebExceptionStatus.RequestProhibitedByProxy: descResult += "This request was not permitted by the proxy."; aShortDescResult += e.Status.ToString(); break; default: descResult += e.Message; aShortDescResult += e.Status.ToString(); break; } Result result = new Result(codeResult, descResult, aShortDescResult); return(result); }
void InitConnection(object state) { HttpWebRequest request = (HttpWebRequest)state; request.WebConnection = this; if (request.ReuseConnection) { request.StoredConnection = this; } if (request.Aborted) { return; } keepAlive = request.KeepAlive; Data = new WebConnectionData(request); retry: Connect(request); if (request.Aborted) { return; } if (status != WebExceptionStatus.Success) { if (!request.Aborted) { request.SetWriteStreamError(status, connect_exception); Close(true); } return; } if (!CreateStream(request)) { if (request.Aborted) { return; } WebExceptionStatus st = status; if (Data.Challenge != null) { goto retry; } Exception cnc_exc = connect_exception; if (cnc_exc == null && (Data.StatusCode == 401 || Data.StatusCode == 407)) { st = WebExceptionStatus.ProtocolError; if (Data.Headers == null) { Data.Headers = new WebHeaderCollection(); } var webResponse = new HttpWebResponse(sPoint.Address, "CONNECT", Data, null); cnc_exc = new WebException(Data.StatusCode == 407 ? "(407) Proxy Authentication Required" : "(401) Unauthorized", null, st, webResponse); } connect_exception = null; request.SetWriteStreamError(st, cnc_exc); Close(true); return; } request.SetWriteStream(new WebConnectionStream(this, request)); }
internal bool HttpAbort(HttpWebRequest request, WebException webException) { Abort(); return(true); }
public Response <System.IO.Stream> Download(SettingsBase userSettings) { if (!mDisposedValue) { StreamDownloadSettings <T> ss = new StreamDownloadSettings <T>(userSettings); DateTime startTime = System.DateTime.Now; HttpWebRequest wr = this.GetWebRequest(ss); byte[] postDataBytes = null; if (userSettings.PostDataInternal != string.Empty) { postDataBytes = System.Text.Encoding.ASCII.GetBytes(userSettings.PostDataInternal); wr.ContentLength = postDataBytes.Length; } mActualDownload = wr; System.IO.MemoryStream memStream = null; System.Net.WebException dlException = null; int size = 0; var headers = new List <KeyValuePair <string, string> >(); DateTime endTime = System.DateTime.Now; try { if (postDataBytes != null) { using (System.IO.Stream s = wr.GetRequestStream()) { s.Write(postDataBytes, 0, postDataBytes.Length); } } using (HttpWebResponse resp = (HttpWebResponse)wr.GetResponse()) { foreach (string header in resp.Headers.Keys) { headers.Add(new KeyValuePair <string, string> (header, resp.Headers[header]));// //headers.Add(header, resp.Headers[header]);//new KeyValuePair<HttpResponseHeader, string>());// } if (userSettings.DownloadResponseStreamInternal) { System.IO.Stream s = resp.GetResponseStream(); endTime = System.DateTime.Now; memStream = MyHelper.CopyStream(s); s.Dispose(); } } if (memStream != null && memStream.CanSeek) { int.TryParse(memStream.Length.ToString(), out size); } } catch (Exception ex) { dlException = this.GetOrCreateWebException(ex, null); } finally { mActualDownload = null; } return(new DefaultResponse <System.IO.Stream>(new ConnectionInfo(dlException, this.Timeout, size, startTime, endTime, headers.ToArray()), memStream)); } else { return(null); } }
internal void SetResponseData(WebConnectionData data) { if (aborted) { if (data.stream != null) { data.stream.Close(); } return; } WebException wexc = null; try { webResponse = new HttpWebResponse(actualUri, method, data, cookieContainer); haveResponse = true; } catch (Exception e) { wexc = new WebException(e.Message, e, WebExceptionStatus.ProtocolError, null); if (data.stream != null) { data.stream.Close(); } } if (wexc == null && (method == "POST" || method == "PUT")) { lock (locker) { CheckSendError(data); if (saved_exc != null) { wexc = (WebException)saved_exc; } } } WebAsyncResult r = asyncRead; if (r != null) { if (wexc != null) { r.SetCompleted(false, wexc); r.DoCallback(); return; } bool redirected; try { redirected = CheckFinalStatus(r); if (!redirected) { r.SetCompleted(false, webResponse); r.DoCallback(); } else { if (webResponse != null) { webResponse.Close(); webResponse = null; } haveResponse = false; webResponse = null; r.Reset(); servicePoint = GetServicePoint(); abortHandler = servicePoint.SendRequest(this, connectionGroup); } } catch (WebException wexc2) { r.SetCompleted(false, wexc2); r.DoCallback(); return; } catch (Exception ex) { wexc = new WebException(ex.Message, ex, WebExceptionStatus.ProtocolError, null); r.SetCompleted(false, wexc); r.DoCallback(); return; } } }
/// <summary> /// 判断当前的请求是不是 <see cref="HttpWebResponse"/> /// </summary> /// <param name="e">包含异常的事件数据</param> /// <returns>如果是 <see cref="HttpWebResponse"/> ,则返回 true</returns> public static bool IsHttpResponse(this WebException e) { return(e.Response != null && e.Response is HttpWebResponse); }
bool Redirect(WebAsyncResult result, HttpStatusCode code) { redirects++; Exception e = null; string uriString = null; switch (code) { case HttpStatusCode.Ambiguous: // 300 e = new WebException("Ambiguous redirect."); break; case HttpStatusCode.MovedPermanently: // 301 case HttpStatusCode.Redirect: // 302 case HttpStatusCode.TemporaryRedirect: // 307 /* MS follows the redirect for POST too * if (method != "GET" && method != "HEAD") // 10.3 * return false; */ contentLength = 0; bodyBufferLength = 0; bodyBuffer = null; method = "GET"; uriString = webResponse.Headers ["Location"]; break; case HttpStatusCode.SeeOther: //303 method = "GET"; uriString = webResponse.Headers ["Location"]; break; case HttpStatusCode.NotModified: // 304 return(false); case HttpStatusCode.UseProxy: // 305 e = new NotImplementedException("Proxy support not available."); break; case HttpStatusCode.Unused: // 306 default: e = new ProtocolViolationException("Invalid status code: " + (int)code); break; } if (e != null) { throw e; } if (uriString == null) { throw new WebException("No Location header found for " + (int)code, WebExceptionStatus.ProtocolError); } Uri prev = actualUri; try { actualUri = new Uri(actualUri, uriString); } catch (Exception) { throw new WebException(String.Format("Invalid URL ({0}) for {1}", uriString, (int)code), WebExceptionStatus.ProtocolError); } hostChanged = (actualUri.Scheme != prev.Scheme || actualUri.Host != prev.Host || actualUri.Port != prev.Port); return(true); }
// Returns true if redirected bool CheckFinalStatus(WebAsyncResult result) { if (result.GotException) { throw result.Exception; } Exception throwMe = result.Exception; bodyBuffer = null; HttpWebResponse resp = result.Response; WebExceptionStatus protoError = WebExceptionStatus.ProtocolError; HttpStatusCode code = 0; if (throwMe == null && webResponse != null) { code = webResponse.StatusCode; if (!authCompleted && ((code == HttpStatusCode.Unauthorized && credentials != null) || (ProxyQuery && code == HttpStatusCode.ProxyAuthenticationRequired))) { if (!usedPreAuth && CheckAuthorization(webResponse, code)) { // Keep the written body, so it can be rewritten in the retry if (InternalAllowBuffering) { bodyBuffer = writeStream.WriteBuffer; bodyBufferLength = writeStream.WriteBufferLength; webResponse.Close(); return(true); } else if (method != "PUT" && method != "POST") { webResponse.Close(); return(true); } writeStream.InternalClose(); writeStream = null; webResponse.Close(); webResponse = null; throw new WebException("This request requires buffering " + "of data for authentication or " + "redirection to be sucessful."); } } if ((int)code >= 400) { string err = String.Format("The remote server returned an error: ({0}) {1}.", (int)code, webResponse.StatusDescription); throwMe = new WebException(err, null, protoError, webResponse); webResponse.ReadAll(); } else if ((int)code == 304 && allowAutoRedirect) { string err = String.Format("The remote server returned an error: ({0}) {1}.", (int)code, webResponse.StatusDescription); throwMe = new WebException(err, null, protoError, webResponse); } else if ((int)code >= 300 && allowAutoRedirect && redirects > maxAutoRedirect) { throwMe = new WebException("Max. redirections exceeded.", null, protoError, webResponse); webResponse.ReadAll(); } } if (throwMe == null) { bool b = false; int c = (int)code; if (allowAutoRedirect && c >= 300) { if (InternalAllowBuffering && writeStream.WriteBufferLength > 0) { bodyBuffer = writeStream.WriteBuffer; bodyBufferLength = writeStream.WriteBufferLength; } b = Redirect(result, code); } if (resp != null && c >= 300 && c != 304) { resp.ReadAll(); } return(b); } if (writeStream != null) { writeStream.InternalClose(); writeStream = null; } webResponse = null; throw throwMe; }