This is a discussion on HTTP Web Response Exception - I cant able to trap. within the Windows Mobile forums, part of the Mobile Software Development category; Hi All I have a .NET CF v2 program which uses asynchronous HttpWebRequest to download a file. During downloading via ...
| |||||||
| Register | FAQ | Members List | Calendar | Mark Forums Read |
| |||
| Hi All I have a .NET CF v2 program which uses asynchronous HttpWebRequest to download a file. During downloading via GPRS if I press and hold the end call key on my WM 5.0 device to close the GPRS connection, the program will crash. I have tried to place HttpWebResponse.GetResponseStream in a Try/Catch block but it does not catch the exception. On the emulator I cannot reproduce this problem. This is the error message I get is: program.exe SocketExecption An operation was attempted on something that is not a socket at System.Net.Sockets.Socket.ReceivedNoCheck() at System.Net.Sockets.Socket.Receive() at System.Net.Connection.Read() at ConnectionClient.Read() at System.Net.HttpReadStream.NetworkRead() at System.Net.ContentLengthReadStream.doRead() at System.Net.HttpReadStream.ReadInternal() at System.Net.HttpReadStream.Read() at System.Net.HttpReadStream.doRead() at WorkItem.doWork() at System.Threading.Timer.ring() Is there a way to catch this exception? Help |
| Sponsored Links |
| |||
| Hi naveen, Quote:
Debugging with ActiveSync and using my PC to connect to the Internet produces different results. * Connecting to the Internet via ActiveSync, debugging is possible. If during downloading midway I close my Internet connection HttpWebResponse returns 0 bytes, no exception is thrown. * Connecting to the Internet using GPRS, debugging is not possible. If during downloading midway I close the GRPS connection (press and hold end call key), program crashes. From the error message it seems that the crash is occurring in System.Net.Sockets and not in my code. Thanks |
| |||
| Quote:
How can I add try/catch in mscorlib.dll, it's not my code |
| |||
| Interesting... How come stack trace shows it without namespace? at System.Net.HttpReadStream.Read() at System.Net.HttpReadStream.doRead() at WorkItem.doWork() at System.Threading.Timer.ring() If that's not your code it might be a bug in NETCF. You might be able to workaround using AppDomain.CurrentDomain.UnhandledException |
| |||
| Thanks John, I just re-checked to make sure I did not miss something. I can confirm it is reporting: at WorkItem.doWork() I do not have any class called WorkItem or any method called doWork. Do you want me to submit a bug to Connect, I should be able to submit some sample code? I will try AppDomain.CurrentDomain.UnhandledException, thanks. |
| |||
| Hi john, thanks for your concern, I have stripped my code to the bare minimum to re-produce the problem, the code is below. Create a new VB. NET project, insert at textbox (TextBox1), label (Label1), and 2 menu items (MenuItem1 and MenuItem2) on the form , then replace the code with the code below. Run program, enter the URL of the file to download in the text box and press MenuItem1 to download. Once a GPRS connection is estabished and downloading has began, press and hold End Call to close GPRS. The error message I posted earlier will appear. Code: Public Class Form1
Private WithEvents m_dm As New DownloadManager
Private Sub MenuItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem2.Click
m_dm.Abort()
Me.Close()
End Sub
Private Sub MenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem1.Click
Me.MenuItem1.Enabled = False
Me.Label1.Text = "Downloading..."
Me.m_dm.DownloadProduct(Me.TextBox1.Text)
End Sub
Private m_receivedBytes As Integer
Private Sub m_downloadService_ProductChuckReceived(ByVal receivedBytes As Integer) Handles m_dm.ProductChuckReceived
m_receivedBytes = receivedBytes
Me.Invoke(New EventHandler(AddressOf ProductChuckReceived))
End Sub
Private Sub ProductChuckReceived(ByVal sender As Object, ByVal e As EventArgs)
Me.Label1.Text = Convert.ToInt32((m_receivedBytes / m_dm.FileSize) * 100) & "%"
End Sub
Private Sub m_downloadService_ProductDownloadedCompleted() Handles m_dm.ProductDownloadedCompleted
Me.Invoke(New EventHandler(AddressOf ProductDownloadedCompleted))
End Sub
Private Sub ProductDownloadedCompleted(ByVal sender As Object, ByVal e As EventArgs)
Me.Label1.Text = "Download complete"
End Sub
End Class
Public NotInheritable Class DownloadManager
Private Const DATA_BLOCK_SIZE As Integer = 65536
Public Event ProductDownloadedCompleted()
Public Event ProductChuckReceived(ByVal receivedBytes As Integer)
Private m_urlRequest As Net.HttpWebRequest = Nothing
Private m_urlResponse As Net.HttpWebResponse
Private m_data() As Byte
Private m_filename As String = ""
Private m_folder As String = "\"
Private m_fileSize As Integer
Private m_fs As IO.FileStream
Private m_abort As Boolean = False
Private m_downloading As Boolean = False
Private m_errMsg As String = ""
Public Sub DownloadProduct(ByVal url As String)
m_abort = False
m_filename = "\" & url.Substring(url.LastIndexOf("/"c) + 1)
m_downloading = True
m_urlRequest = CType(Net.HttpWebRequest.Create(url), Net.HttpWebRequest)
m_urlRequest.Timeout = 20000
m_urlRequest.Method = "GET"
m_urlRequest.KeepAlive = False
m_urlRequest.BeginGetResponse(New AsyncCallback(AddressOf ResponseReceived), Nothing)
End Sub
Private Sub ResponseReceived(ByVal ar As IAsyncResult)
If m_abort = False Then
Try
m_urlResponse = CType(m_urlRequest.EndGetResponse(ar), Net.HttpWebResponse)
m_data = New Byte(DATA_BLOCK_SIZE) {}
m_fileSize = Convert.ToInt32(m_urlResponse.ContentLength)
If IO.File.Exists(m_filename) Then
IO.File.Delete(m_filename)
End If
m_fs = New IO.FileStream(m_filename, IO.FileMode.Create)
Catch ex As Net.WebException
m_errMsg = ex.Message
Catch ex As IO.IOException
m_errMsg = ex.Message
End Try
End If
If m_abort OrElse m_errMsg <> "" Then
Else
RaiseEvent ProductChuckReceived(0)
m_urlResponse.GetResponseStream().BeginRead(m_data, 0, DATA_BLOCK_SIZE, New AsyncCallback(AddressOf OnDataRead), Me)
End If
End Sub
Sub OnDataRead(ByVal res As IAsyncResult)
If m_abort = False Then
Dim bytesWrite As Integer = m_urlResponse.GetResponseStream().EndRead(res)
m_fs.Write(m_data, 0, bytesWrite)
If bytesWrite > 0 Then
If m_abort = False Then
RaiseEvent ProductChuckReceived(Convert.ToInt32(m_fs.Position))
Try
m_urlResponse.GetResponseStream().BeginRead(m_data, 0, DATA_BLOCK_SIZE, New AsyncCallback(AddressOf OnDataRead), Me)
Catch ex As Exception
End Try
End If
Else
If m_fs.Length <> Me.m_fileSize Then
m_abort = True
Me.m_errMsg = "Error downloading file."
End If
m_urlResponse.Close()
m_urlRequest.Abort()
m_urlResponse.GetResponseStream.Close()
If m_abort = False Then
m_fs.Close()
m_fs = Nothing
RaiseEvent ProductDownloadedCompleted()
End If
End If
End If
If m_abort Then
m_fs.Close()
m_fs = Nothing
Try
If IO.File.Exists(m_filename) Then
IO.File.Delete(m_filename)
End If
Catch ex As Exception
End Try
End If
End Sub
Public Sub Abort()
m_abort = True
If m_downloading Then
m_urlRequest.Abort()
m_urlRequest = Nothing
m_urlResponse.Close()
m_urlResponse = Nothing
End If
End Sub
Public ReadOnly Property FileSize() As Integer
Get
Return m_fileSize
End Get
End Property
Public Function Aborted() As Boolean
Return m_abort
End Function
End Class |
| |||
| Hi all, I created 2 web services with VB.NET. When I test them in the automatically-generated aspx page, there's no problem. However, when I try to call them from a program, I get the following error: The request failed with HTTP status 401: Access Denied. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Net.WebException: The request failed with HTTP status 401: Access Denied. -- When I turn on the trace I get this info: Line 69: System.Web.Services.Protocols.SoapDocumentMethodAt tribute("http://tempuri.or g/BrowseDestinations", Use:=System.Web.Services.Description.SoapBindingUs e.Literal, parameterstyle:=system.web.services.protocols.soap parameterstyle.wrapped)> _ Line 70: Public Function BrowseDestinations(ByVal StartDate As String, ByVal EndDate As String, ByVal Categories As String) As System.Data.DataSet -->Line 71: Dim results() As Object = Me.Invoke("BrowseDestinations", New Object() {StartDate, EndDate,Categories}) Line 72: Return CType(results(0),System.Data.DataSet) Line 73: End Function -- The Line 71 raise the authentication error. This piece of code corresponds to the proxy that VS.NET generates for the web service. As you can see this is a security error caused by the automatically-generated proxy and to be honest with you people, I would be needing the 'Complete Idiot Guide' to solve it as I'm a newbie when it comes to set access permitions in Windows 2000. I have both anonymous access and integrated Windows auth checked for the web directory hosting my web services. Do i have to change wy config.web or anything like that? Thanks in advance for any help |
| |||
| I have exactly the same problem. I receive the 401 http error while doing the walkthrough "Accessing an XML Web Servive using visual Basic or Visual C#" (I did it with C#). I tried to uncheck the "Integrated Windows Authentication" option in IIS but it didn't work! Here is the error I received from the Web Service: Server Error in '/TempConvertClient2' Application. -------------------------------------------------------------------------------- The request failed with HTTP status 401: Access Denied. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Net.WebException: The request failed with HTTP status 401: Access Denied. Source Error: Line 35: [System.Web.Services.Protocols.SoapDocumentMethodAt tribute("http://Walkthrough/XmlWebServices/ConvertTemperature", RequestNamespace="http://Walkthrough/XmlWebServices/", ResponseNamespace="http://Walkthrough/XmlWebServices/", Use=System.Web.Services.Description.SoapBindingUse .Literal, ParameterStyle=System.Web.Services.Protocols.SoapP arameterStyle.Wrapped)] Line 36: public System.Double ConvertTemperature(System.Double dFahrenheit) { Line 37: object[] results = this.Invoke("ConvertTemperature", new object[] { Line 38: dFahrenheit}); Line 39: return ((System.Double)(results[0])); Source File: c:\inetpub\wwwroot\TempConvertClient2\Web References\ConvertSvc\Reference.cs Line: 37 Stack Trace: [WebException: The request failed with HTTP status 401: Access Denied.] System.Web.Services.Protocols.SoapHttpClientProtoc ol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream) +1174 System.Web.Services.Protocols.SoapHttpClientProtoc ol.Invoke(String methodName, Object[] parameters) +216 TempConvertClient2.ConvertSvc.Service1.ConvertTemp erature(Double dFahrenheit) in c:\inetpub\wwwroot\TempConvertClient2\Web References\ConvertSvc\Reference.cs:37 TempConvertClient2.WebForm1.Button1_Click(Object sender, EventArgs e) in c:\inetpub\wwwroot\tempconvertclient2\webform1.asp x.cs:54 System.Web.UI.WebControls.Button.OnClick(EventArgs e) +108 System.Web.UI.WebControls.Button.System.Web.UI.IPo stBackEventHandler.RaisePostBackEvent(St ring eventArgument) +58 System.Web.UI.Page.RaisePostBackEvent(IPostBackEve ntHandler sourceControl, String eventArgument) +18 System.Web.UI.Page.RaisePostBackEvent(NameValueCol lection postData) +33 System.Web.UI.Page.ProcessRequestMain() +1263 |
| |||
| You need to set the Credentials property of your service. To pass the system credentials for the current security context, you can use CredentialCache.DefaultCredentials. For a service named SimpleService, it would look something like this: [C#] SimpleService ss = new SimpleService(); ss.Credentials = System.Net.CredentialCache.DefaultCredentials;
__________________ Raja. Myblog |
| |||
| The call to System.Net.CredentialCache.GetCredential by the underlying web services code will get a null w/o setting the value described below. That being the case, does anyone know why in every web service example I've seen this is never mentioned? Adding it works for both WinForm and ASP.NET as seems to be required in each. Anyone have any background why this is never mentioned since this is so critical to making web service calls work. Thanks! |
| |||
| I have code as follows - href = "URL" // Create a request for the URL. WebRequest request = WebRequest.Create(href); //Set the USerAgent ((HttpWebRequest)request).UserAgent = "msie"; // Get the response. WebResponse response = request.GetResponse(); Sometimes the code "WebResponse response = request.GetResponse();" is giving time out error. Please let me know how can I handle this situation.
__________________ Venkat knowledge is Power |
| |||
| Catch the exception It would be more useful to see a complete program. It could be a programming error, or maybe the connection to the remote site is really timing out. Are you disposing all WebResponse objects? |
| |||
| This the modified code - I have chnaged the code still also I am getting the error // Create a request for the URL. WebRequest request = WebRequest.Create("URL"); //Add the User Agent ((HttpWebRequest)request).UserAgent = "msie" //Time out ((HttpWebRequest)request).Timeout = 600000; //Time out ((HttpWebRequest)request).ReadWriteTimeout = 600000; //set alive = true ((HttpWebRequest)request).KeepAlive = true; //auto redirect = true ((HttpWebRequest)request).AllowAutoRedirect = true; // Get the response. WebResponse response = request.GetResponse(); I am getting the error in the line - "WebResponse response = request.GetResponse();" Full program goes as follows - XmlTextReader xmlTextReader = null; // Create a request for the URL. WebRequest request = WebRequest.Create(href); //Set the USerAgent ((HttpWebRequest)request).UserAgent = ConfigurationSettings.AppSettings["USER_AGENT"].ToString(); //Time out ((HttpWebRequest)request).Timeout = Convert.ToInt32(ConfigurationSettings.AppSettings["URL_TIME_OUT"].ToString()); //Time out ((HttpWebRequest)request).ReadWriteTimeout = Convert.ToInt32(ConfigurationSettings.AppSettings["URL_TIME_OUT"].ToString()); //set alive = true ((HttpWebRequest)request).KeepAlive = true; //auto redirect = true ((HttpWebRequest)request).AllowAutoRedirect = true; // Get the response. WebResponse response = request.GetResponse(); // Get the stream containing content returned by the server. Stream dataStream = response.GetResponseStream(); //XmlTextReader xmlTextReader = new XmlTextReader(dataStream);
__________________ Venkat knowledge is Power |
| |||
| That's just more code, not a program—is that code executed in a loop, is there any exception handling, etc.? At least, make sure to wrap your code that uses the WebResponse and the response Stream in a C# using block: Code: using (WebResponse response = request.GetResponse())
using (Stream responseStream = response.GetResponseStream())
{
// Read from responseStream
} |