Saturday, March 24, 2012
System.Net.WebClient Best Practices
anyone could point to the good resource for Best Practices with this object.
The two things I haven't seen in sample code are:
1. How to retrieve connection error messages, such as a DNS resolution error
or connection dropped errors.
2. Should I use the Dispose or Finalize methods to destroy the object when I
done? I assume that the object uses unmanaged code at some point to connect
to another server. So do I need to use the Finalize method release those
other objects?
Here is a function from one of my projects:
Private Function getRemoteDat() As Boolean
Dim CCPostURL As String =
ConfigurationSettings.AppSettings("https://www.remoteData.com/process.asp")
Dim Status As Boolean = False ' Assumes failure until set to True
Dim ResponseResults As String
Dim responseString As String
Dim myWebClient As New System.Net.WebClient
Dim responseArray As Byte()
Dim myNameValueCollection As New
System.Collections.Specialized.NameValueCollection
Dim ResultMsg As String
Dim splitResponse() As String
myNameValueCollection.Add("first_name", txtBillFName.Text)
myNameValueCollection.Add("last_name", txtBillLName.Text)
myNameValueCollection.Add("address", txtBillAdd1.Text)
Try
responseArray = myWebClient.UploadValues(CCPostURL, "POST",
myNameValueCollection) 'Sends request to Gateway
responseString = System.Text.Encoding.ASCII.GetString(responseArray)
'Converts bit array to string
splitResponse = Split(responseString, System.Environment.NewLine)
'Splits response into string array
ResultMsg = splitResponse(1).Remove(0, 19) 'Gets Result Message
Catch
Status = False 'Connection failed or response was corrupted
End Try
If ResultMsg = "APPROVED" Then
_GatewayApprovalString = splitResponse(2) & "|" & splitResponse(3)
'Set string if successful
Status = True
Else
Status = False
End If
Return Status
End FunctionHi jmh,
Welcome to ASP.NET newsgroup.
Regarding on the "System.Net.WebClient Best Practices" you mentioned, here
are some of my suggestions:
The WebClient class in system.net namespace is a well-encapsulated class
which just simulate the IE browser's behavior. When we use it to post data
or retrieve response from remote url, it will help do the underlying
connection and transfering tasks for us(also some additinal works such as
cookie management). In fact, the WebClient class is using the
HttpWebRequest class internally when dealing with http... resource. So if
we need more detailed and
underlying control when doing such work, we can consider directly use the
HttpWebRequest class instead. This class can help us manually write binary
data into the http request's stream and customize the http Message's header
Also, we can get the http status code after we make request and retieve
response from the remote resource. For detailed reference on
HttpWebRequest , you can lookup the MSDN document on it(or the accessing
internet section in "programming with .net section).
In addition, since httpWebrequest have more underlying controls, it also
require us to do more works to properly handle the resource. for example,
we need to manually close the response stream after read it so as not to
occupy the connection. Here are some tech articles and former newsgroup
threads discussing on such problems, such as use httpwebrequest to post
data, upload file or upload files together with form datas:
#Send data from non browser client (using HttpWebRequest) that can be used
by access web page controls.
http://weblogs.asp.net/ngur/archive.../11/129951.aspx
#how to upload file via c# code
http://groups-beta.google.com/group...anguages.csharp
/browse_thread/thread/eea92e16a26fbdc0/474b6a3fcd63dd93?q=C%23+upload+file+s
teven+cheng&rnum=1&hl=en#474b6a3fcd63dd93
Steven Cheng
Microsoft Online Support
Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)
System.Net.WebClient Best Practices
anyone could point to the good resource for Best Practices with this object.
The two things I haven't seen in sample code are:
1. How to retrieve connection error messages, such as a DNS resolution error
or connection dropped errors.
2. Should I use the Dispose or Finalize methods to destroy the object when I
done? I assume that the object uses unmanaged code at some point to connect
to another server. So do I need to use the Finalize method release those
other objects?
Here is a function from one of my projects:
Private Function getRemoteDat() As Boolean
Dim CCPostURL As String =
ConfigurationSettings.AppSettings("https://www.remoteData.com/process.asp")
Dim Status As Boolean = False ' Assumes failure until set to True
Dim ResponseResults As String
Dim responseString As String
Dim myWebClient As New System.Net.WebClient
Dim responseArray As Byte()
Dim myNameValueCollection As New
System.Collections.Specialized.NameValueCollection
Dim ResultMsg As String
Dim splitResponse() As String
myNameValueCollection.Add("first_name", txtBillFName.Text)
myNameValueCollection.Add("last_name", txtBillLName.Text)
myNameValueCollection.Add("address", txtBillAdd1.Text)
Try
responseArray = myWebClient.UploadValues(CCPostURL, "POST",
myNameValueCollection) 'Sends request to Gateway
responseString = System.Text.Encoding.ASCII.GetString(responseArray )
'Converts bit array to string
splitResponse = Split(responseString, System.Environment.NewLine)
'Splits response into string array
ResultMsg = splitResponse(1).Remove(0, 19) 'Gets Result Message
Catch
Status = False 'Connection failed or response was corrupted
End Try
If ResultMsg = "APPROVED" Then
_GatewayApprovalString = splitResponse(2) & "|" & splitResponse(3)
'Set string if successful
Status = True
Else
Status = False
End If
Return Status
End FunctionHi jmh,
Welcome to ASP.NET newsgroup.
Regarding on the "System.Net.WebClient Best Practices" you mentioned, here
are some of my suggestions:
The WebClient class in system.net namespace is a well-encapsulated class
which just simulate the IE browser's behavior. When we use it to post data
or retrieve response from remote url, it will help do the underlying
connection and transfering tasks for us(also some additinal works such as
cookie management). In fact, the WebClient class is using the
HttpWebRequest class internally when dealing with http... resource. So if
we need more detailed and
underlying control when doing such work, we can consider directly use the
HttpWebRequest class instead. This class can help us manually write binary
data into the http request's stream and customize the http Message's header
Also, we can get the http status code after we make request and retieve
response from the remote resource. For detailed reference on
HttpWebRequest , you can lookup the MSDN document on it(or the accessing
internet section in "programming with .net section).
In addition, since httpWebrequest have more underlying controls, it also
require us to do more works to properly handle the resource. for example,
we need to manually close the response stream after read it so as not to
occupy the connection. Here are some tech articles and former newsgroup
threads discussing on such problems, such as use httpwebrequest to post
data, upload file or upload files together with form datas:
#Send data from non browser client (using HttpWebRequest) that can be used
by access web page controls.
http://weblogs.asp.net/ngur/archive.../11/129951.aspx
#how to upload file via c# code
http://groups-beta.google.com/group...anguages.csharp
/browse_thread/thread/eea92e16a26fbdc0/474b6a3fcd63dd93?q=C%23+upload+file+s
teven+cheng&rnum=1&hl=en#474b6a3fcd63dd93
Steven Cheng
Microsoft Online Support
Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)
System.Net.WebClient and UploadFile() Problem
making looks as follows:
webClient.UploadFile("http://sdtpcal.someserver.com/Federation/Databases/Fed
eration.Zip",
@dotnet.itags.org."C:\Temp\Federation.Zip");
'Federation' is a virtual directory on the server I'm attempting to upload
the file to. The URL is valid and the file I'm attempting to transfer
exists. I keep getting 404 errors (not found). It's not clear to me exactly
what cannot be found. If I attempt to download this exact file from the same
exact URL using webClient.DownloadFile, it works fine!
Thanks for the help - Amos.You can not simply upload file on a server.
Something should wait for that file at the server end.
So url http://sdtpcal.someserver.com/Feder.../Federation.Zip to
download file looks correct.
but to upload you must write an ASPX page that will accept file and save to
the folder on a server.
George.
"Amos Soma" <amos_j_soma@.yahoo.com> wrote in message
news:OqGt9oK7GHA.1248@.TK2MSFTNGP03.phx.gbl...
>I am using WebClient to upload a file to a remote server. The call I'm
>making looks as follows:
> webClient.UploadFile("http://sdtpcal.someserver.com/Federation/Databases/F
ederation.Zip",
> @."C:\Temp\Federation.Zip");
> 'Federation' is a virtual directory on the server I'm attempting to upload
> the file to. The URL is valid and the file I'm attempting to transfer
> exists. I keep getting 404 errors (not found). It's not clear to me
> exactly what cannot be found. If I attempt to download this exact file
> from the same exact URL using webClient.DownloadFile, it works fine!
> Thanks for the help - Amos.
>
Thus wrote George Ter-Saakov,
> You can not simply upload file on a server.
> Something should wait for that file at the server end.
> So url
> http://sdtpcal.someserver.com/Feder.../Federation.Zip to
> download file looks correct.
> but to upload you must write an ASPX page that will accept file and
> save to the folder on a server.
You only need a web application endpoint for POST requests. If the OP can
use PUT, the web server may support this without any special user code (IIS
does for sure).
Both WebClient.UploadFile(uri, "PUT", fileName) and WebClient.OpenWrite(uri,
"PUT") will do the trick.
Cheers,
--
Joerg Jooss
news-reply@.joergjooss.de
System.Net.WebClient and UploadFile() Problem
making looks as follows:
webClient.UploadFile("http://sdtpcal.someserver.com/Federation/Databases/Federation.Zip",
@dotnet.itags.org."C:\Temp\Federation.Zip");
'Federation' is a virtual directory on the server I'm attempting to upload
the file to. The URL is valid and the file I'm attempting to transfer
exists. I keep getting 404 errors (not found). It's not clear to me exactly
what cannot be found. If I attempt to download this exact file from the same
exact URL using webClient.DownloadFile, it works fine!
Thanks for the help - Amos.You can not simply upload file on a server.
Something should wait for that file at the server end.
So url http://sdtpcal.someserver.com/Feder.../Federation.Zip to
download file looks correct.
but to upload you must write an ASPX page that will accept file and save to
the folder on a server.
George.
"Amos Soma" <amos_j_soma@.yahoo.comwrote in message
news:OqGt9oK7GHA.1248@.TK2MSFTNGP03.phx.gbl...
Quote:
Originally Posted by
>I am using WebClient to upload a file to a remote server. The call I'm
>making looks as follows:
>
webClient.UploadFile("http://sdtpcal.someserver.com/Federation/Databases/Federation.Zip",
@."C:\Temp\Federation.Zip");
>
'Federation' is a virtual directory on the server I'm attempting to upload
the file to. The URL is valid and the file I'm attempting to transfer
exists. I keep getting 404 errors (not found). It's not clear to me
exactly what cannot be found. If I attempt to download this exact file
from the same exact URL using webClient.DownloadFile, it works fine!
>
Thanks for the help - Amos.
>
>
Thus wrote George Ter-Saakov,
Quote:
Originally Posted by
You can not simply upload file on a server.
Something should wait for that file at the server end.
So url
http://sdtpcal.someserver.com/Feder.../Federation.Zip to
download file looks correct.
>
but to upload you must write an ASPX page that will accept file and
save to the folder on a server.
You only need a web application endpoint for POST requests. If the OP can
use PUT, the web server may support this without any special user code (IIS
does for sure).
Both WebClient.UploadFile(uri, "PUT", fileName) and WebClient.OpenWrite(uri,
"PUT") will do the trick.
Cheers,
--
Joerg Jooss
news-reply@.joergjooss.de
System.Net.WebException:
I am trying to make a simple file updload WinForm app.
Here's the code:
WebClient webClient = new WebClient();
webClient.UploadFile(new Uri("http://localhost/WebSite/Upload.aspx"),
"c:\\bin.zip");
My IIS 5.1 Web server uses default configuration.
If the file is less than 5Mo everything works fine. If the file is too big I
get this exception:
System.Net.WebException: The underlying connection was closed: An unexpected
error occurred on a receive. --> System.IO.IOException: Unable to read data
from the transport connection: An existing connection was forcibly closed by
the remote host. --> System.Net.Sockets.SocketException: An existing
connection was forcibly closed by the remote host
I will never have to upload more than 30Mo.
Do you now how I can correct this issue ?In the web.config file, the httpRunTime element has a maxRequestLength which
restricts the length in bytes of any HTTP request. The default is 4MB.
--
HTH,
Kevin Spencer
Microsoft MVP
Professional Numbskull
Hard work is a medication for which
there is no placebo.
"zolof" <zolof@.discussions.microsoft.com> wrote in message
news:C12D293F-C3B4-401C-99A6-7A10DB48B8BE@.microsoft.com...
> Hi,
> I am trying to make a simple file updload WinForm app.
> Here's the code:
> WebClient webClient = new WebClient();
> webClient.UploadFile(new Uri("http://localhost/WebSite/Upload.aspx"),
> "c:\\bin.zip");
> My IIS 5.1 Web server uses default configuration.
> If the file is less than 5Mo everything works fine. If the file is too big
> I
> get this exception:
> System.Net.WebException: The underlying connection was closed: An
> unexpected
> error occurred on a receive. --> System.IO.IOException: Unable to read
> data
> from the transport connection: An existing connection was forcibly closed
> by
> the remote host. --> System.Net.Sockets.SocketException: An existing
> connection was forcibly closed by the remote host
> I will never have to upload more than 30Mo.
> Do you now how I can correct this issue ?
That's great. Thanks a lot for your help.
System.Net.WebException:
I am trying to make a simple file updload WinForm app.
Here's the code:
WebClient webClient = new WebClient();
webClient.UploadFile(new Uri("http://localhost/WebSite/Upload.aspx"),
"c:\\bin.zip");
My IIS 5.1 Web server uses default configuration.
If the file is less than 5Mo everything works fine. If the file is too big I
get this exception:
System.Net.WebException: The underlying connection was closed: An unexpected
error occurred on a receive. --> System.IO.IOException: Unable to read data
from the transport connection: An existing connection was forcibly closed by
the remote host. --> System.Net.Sockets.SocketException: An existing
connection was forcibly closed by the remote host
I will never have to upload more than 30Mo.
Do you now how I can correct this issue ?In the web.config file, the httpRunTime element has a maxRequestLength which
restricts the length in bytes of any HTTP request. The default is 4MB.
HTH,
Kevin Spencer
Microsoft MVP
Professional Numbskull
Hard work is a medication for which
there is no placebo.
"zolof" <zolof@.discussions.microsoft.com> wrote in message
news:C12D293F-C3B4-401C-99A6-7A10DB48B8BE@.microsoft.com...
> Hi,
> I am trying to make a simple file updload WinForm app.
> Here's the code:
> WebClient webClient = new WebClient();
> webClient.UploadFile(new Uri("http://localhost/WebSite/Upload.aspx"),
> "c:\\bin.zip");
> My IIS 5.1 Web server uses default configuration.
> If the file is less than 5Mo everything works fine. If the file is too big
> I
> get this exception:
> System.Net.WebException: The underlying connection was closed: An
> unexpected
> error occurred on a receive. --> System.IO.IOException: Unable to read
> data
> from the transport connection: An existing connection was forcibly closed
> by
> the remote host. --> System.Net.Sockets.SocketException: An existing
> connection was forcibly closed by the remote host
> I will never have to upload more than 30Mo.
> Do you now how I can correct this issue ?
>
That's great. Thanks a lot for your help.