.NET Framework 4 VB.Net Call an API - asp.net

I am working in an "old" VB.Net application. I wish to make a call to an API, check if I got a 404, parse the JSON result and all the other usual things you can do with an API call.
What is the cleanest way of doing this? I thought I can use the HttpClient class, but I can't apparently! VS 2017 is not giving me the option of adding System.Net.Http as an Import.
CODE
Right now I'm doing this which seems messy.
Public Function GetUserInfo(ByVal authTokenBytes As Byte()) As WebPayWS.GetUserInfoResult
Dim token As New token
token.token1 = authTokenBytes
Dim userInformation As GetUserInfoResult = _myService.GetUserInfo(token)
If AccountExists(userInformation.accountno) Then
Dim response As String = GetAccountInfoFromApi(userInformation.accountno)
End If
Return userInformation
End Function
Private Function GetAccountInfoFromApi(accountno As String) As String
Dim accountInformationUrl As String = "URL"
Dim webClient As WebClient = New WebClient()
Return webClient.DownloadString(New Uri(accountInformationUrl))
End Function
Am I stuck with WebClient? If yes, how do I check for a 404 using WebClient?

You can wrap it in an exception with the WebClient check this out
Private Function GetAccountInfoFromApi(accountno As String) As String
Dim accountInformationUrl As String = "URL"
Dim webClient As WebClient = New WebClient()
'Return webClient.DownloadString(New Uri(accountInformationUrl))
Dim retString As String
Try
retString = webClient.DownloadString(New Uri(accountInformationUrl))
Catch ex As WebException
If ex.Status = WebExceptionStatus.ProtocolError AndAlso ex.Response IsNot Nothing Then
Dim resp = DirectCast(ex.Response, HttpWebResponse)
If resp.StatusCode = HttpStatusCode.NotFound Then
' HTTP 404
'other steps you want here
End If
End If
'throw any other exception - this should not occur
Throw
End Try
Return retString
End Function

Add a reference first
Right click on project
Add...
Reference...
Browse
C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies\System.Net.Http.dll
Ok
Now, you can import
Imports System.Net.Http
You can also use NuGet, see https://stackoverflow.com/a/13668810/832052

Related

Managing licenses for Office 365 in vb.net

I am trying to run Office365 cmdlets in a vb.net webservice project.The code is:
Public Function ExcutePowershellCommands() As ObjectModel.Collection(Of PSObject)
Try
Dim userList As ObjectModel.Collection(Of PSObject) = Nothing
Dim initialSession As InitialSessionState = InitialSessionState.CreateDefault()
initialSession.ImportPSModule(New String() {"MSOnline"})
Dim O365Password_secureString As New System.Security.SecureString()
Dim O365Password As String = "password"
For Each x As Char In O365Password
O365Password_secureString.AppendChar(x)
Next
Dim credential As New PSCredential("username", O365Password_secureString)
Dim connectCommand As New Command("Connect-MsolService")
connectCommand.Parameters.Add((New CommandParameter("Credential", credential)))
Dim getCommand As New Command("Get-MsolUser")
Using psRunSpace As Runspace = RunspaceFactory.CreateRunspace(initialSession)
psRunSpace.Open()
For Each com As Command In New Command() {connectCommand, getCommand}
Dim pipe As Pipeline = psRunSpace.CreatePipeline()
pipe.Commands.Add(com)
Dim results As ObjectModel.Collection(Of PSObject) = pipe.Invoke()
Dim [error] As ObjectModel.Collection(Of Object) = pipe.[Error].ReadToEnd()
If [error].Count > 0 AndAlso com.Equals(connectCommand) Then
Throw New ApplicationException("Problem in login! " + [error](0).ToString())
Return Nothing
End If
If [error].Count > 0 AndAlso com.Equals(getCommand) Then
Throw New ApplicationException("Problem in getting data! " + [error](0).ToString())
Return Nothing
Else
userList = results
End If
Next
psRunSpace.Close()
End Using
Return userList
Catch generatedExceptionName As Exception
Throw
End Try
End Function
When Connect-MsolService is run, I get this error message:
There was no endpoint listening at https://provisioningapi.microsoftonline.com/provisioningwebservice.svc that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.
I can run this function successfully within a windows App. I think some thing might be wrong in IIS. any idea?

New Google Recaptcha with ASP.Net

I am attempting to get the new Google reCaptcha working in my ASP.NET project and I am having problems getting it to be the new one "I'm not a robot".
I had the old one in there and after doing much research on the developers.google.com web site, everything looks the same (they even point me to a download of the same dll - 1.0.5). So, I got the new keys and put them in and it works but it looks just like the old reCaptcha.
Has anyone gotten the new one to work with their ASP.Net? What am I missing?
EDIT:
So playing around in a test app and searching some other web sites I found that if I create a page like this:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>reCAPTCHA demo: Simple page</title>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<form id="form1" runat="server" action="?" method="POST">
<div>
<div class="g-recaptcha" data-sitekey="My Public Key"></div>
<br/>
<asp:Button ID="Button1" runat="server" Text="Submit" />
</div>
</form>
</body>
</html>
And then in my code-behind (Button1_Click), I do this:
Dim Success As Boolean
Dim recaptchaResponse As String = request.Form("g-recaptcha-response")
If Not String.IsNullOrEmpty(recaptchaResponse) Then
Success = True
Else
Success = False
End If
The recaptchaResponse will either be empty or filled in depending on if they are a bot or not. The issue is, I now need to take this response and send it to google with my private key so I can verify that the response was not provided by a bot, in my code-behind, but I cannot figure out how. I tried this (in place of Success = True):
Dim client As New System.Net.Http.HttpClient()
client.BaseAddress = New Uri("https://www.google.com/recaptcha/")
client.DefaultRequestHeaders.Accept.Clear()
client.DefaultRequestHeaders.Accept.Add(New Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"))
Dim response As Net.Http.HttpResponseMessage = Await client.GetAsync("api/siteverify?secret=My Private key&response=" + recaptchaResponse)
If (response.IsSuccessStatusCode) Then
Dim CaptchResponse As ReCaptchaModel = Await response.Content.ReadAsAsync(Of ReCaptchaModel)()
Success = CaptchResponse.success
Else
Success = False
End If
But, I could not figure out how to get the async stuff working and I cannot find anything on what ReCaptchaModel is, so I found another way to call a web service and get a json response and tried this instead:
Dim request As Net.WebRequest = Net.WebRequest.Create("https://www.google.com/recaptcha/")
Dim Data As String = "api/siteverify?secret=My Private Key&response=" + recaptchaResponse
request.Method = "POST"
request.ContentType = "application/json; charset=utf-8"
Dim postData As String = "{""data"":""" + Data + """}"
'get a reference to the request-stream, and write the postData to it
Using s As IO.Stream = request.GetRequestStream()
Using sw As New IO.StreamWriter(s)
sw.Write(postData)
End Using
End Using
'get response-stream, and use a streamReader to read the content
Using s As IO.Stream = request.GetResponse().GetResponseStream()
Using sr As New IO.StreamReader(s)
'decode jsonData with javascript serializer
Dim jsonData = sr.ReadToEnd()
Stop
End Using
End Using
But, this just gives me the content of the web page at https://www.google.com/recaptcha. Not what I want. The Google page isn't very useful and I am stuck on where to go. I need some help either calling the Google verify service or if anyone has found another way to do this from ASP.NET.
I had just about given up when I ran across something unrelated that made me think about it again and in a different way. In my last attempt above, I was attempting to pass the private key and recaptcha response as the data, so I tried it in the create of the WebRequest and it worked. Here is the final solution:
Using the same HTML posted above, I created a function that I can call in the button click event where I check the Page.IsValid and call this function:
Private Function IsGoogleCaptchaValid() As Boolean
Try
Dim recaptchaResponse As String = Request.Form("g-recaptcha-response")
If Not String.IsNullOrEmpty(recaptchaResponse) Then
Dim request As Net.WebRequest = Net.WebRequest.Create("https://www.google.com/recaptcha/api/siteverify?secret=My Private Key&response=" + recaptchaResponse)
request.Method = "POST"
request.ContentType = "application/json; charset=utf-8"
Dim postData As String = ""
'get a reference to the request-stream, and write the postData to it
Using s As IO.Stream = request.GetRequestStream()
Using sw As New IO.StreamWriter(s)
sw.Write(postData)
End Using
End Using
''get response-stream, and use a streamReader to read the content
Using s As IO.Stream = request.GetResponse().GetResponseStream()
Using sr As New IO.StreamReader(s)
'decode jsonData with javascript serializer
Dim jsonData = sr.ReadToEnd()
If jsonData = "{" & vbLf & " ""success"": true" & vbLf & "}" Then
Return True
End If
End Using
End Using
End If
Catch ex As Exception
'Dont show the error
End Try
Return False
End Function
I'm sure there are improvements to be made to the code, but it works. I couldn't see adding references to some JSON libraries for reading one thing I just check the string.
Thank you for sharing this. It worked for me. I went ahead and converted it to C# (since that's what I was using) and added a few things.
I changed the validation step. I split the JSON string and evaluated if success was found where it should be.
I used the ConfigurationManager to store the ReCaptcha Keys.
Finally, I changed it from using a WebRequest to using and HttpClient. This cut the code in half because I don't need to read the stream now.
Feel free to use this code as well.
private static bool IsReCaptchaValid(string response)
{
if (string.IsNullOrWhiteSpace(response))
{
return false;
}
var client = new HttpClient();
string result =
client.GetStringAsync(string.Format("{0}?secret={1}&response={2}", ConfigurationManager.AppSettings["ReCaptchaValidationLink"],
ConfigurationManager.AppSettings["ReCaptchaSecretKey"], response)).Result;
string[] split = result.Split('\"');
return split[1] == "success";
}
I took a slightly different approach, using the data-callback option and a Session parameter. The following sits within the MainContent block of the .aspx file:
<asp:ScriptManager ID="scrEnablePage" EnablePageMethods="true" runat="server" />
<asp:Panel ID="pnlCaptcha" runat="server" Visible="true">
<div class="g-recaptcha"
data-sitekey='<asp:Literal ID="litKey" runat="server" Text="<%$ AppSettings:recaptchaPublicKey%>" />'
data-callback="handleCaptcha"></div>
</asp:Panel>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script type="text/javascript">
function handleCaptcha(e) {
PageMethods.RecaptchaValid(e);
location.reload(true);
}
</script>
Then in the code-behind:
Private Const GoogleUrl As String = "https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}"
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
pnlCaptcha.Visible = Not (Session("VerifiedHuman") = "True")
...
End Sub
<System.Web.Services.WebMethod(EnableSession:=True)> _
Public Shared Sub RecaptchaValid(response As String)
Dim client As New System.Net.WebClient()
Dim outcome As Dictionary(Of String, String)
Dim result As String = String.Join(vbCrLf,
{"{", """success"": true", "}"})
Dim serializer As New System.Web.Script.Serialization.JavaScriptSerializer()
Dim url As String = String.Format(GoogleUrl,
ConfigurationManager.AppSettings.Get("recaptchaPrivateKey"),
response)
Try
result = client.DownloadString(url)
Catch ex As System.Net.WebException
Exit Sub ' Comment out to default to passing
End Try
outcome = serializer.Deserialize(Of Dictionary(Of String, String))(result)
HttpContext.Current.Session("VerifiedHuman") = outcome("success")
End Sub
Now in Page_Load you can check Session("VerifiedHuman") = "True" and update your page controls accordingly, hiding the panel with the Captcha control and showing the other appropriate items.
Note that this takes the keys from Web.config, i.e.
<configuration>
<appSettings>
<add key="recaptchaPublicKey" value="..." />
<add key="recaptchaPrivateKey" value="..." />
...
</appSettings>
...
</configuration>
This adds a few things. It converts the response from Google into a Json object, it adds a timeout on the verification request, and it adds a verification of the hostname (required by Google if sending requests from multiple domains and the domains aren't listed in the Google Admin area).
Imports Newtonsoft.Json
Public Class Google
Public Class ReCaptcha
Private Const secret_key = "YOUR_SECRET_KEY"
Public Shared Function Validate(Request As HttpRequest, hostname As String) As Boolean
Dim g_captcha_response = Request.Form("g-recaptcha-response")
If Not String.IsNullOrEmpty(g_captcha_response) Then
Dim response = ExecuteVerification(g_captcha_response)
If Not response.StartsWith("ERROR:") Then
Dim json_obj = JsonConvert.DeserializeObject(Of ValidateResponse)(response)
If json_obj.success Then
If json_obj.hostname.ToLower = hostname.ToLower Then Return True
End If
End If
End If
Return False
End Function
Private Shared Function ExecuteVerification(g_captcha_response As String) As String
Dim request As Net.WebRequest = Net.WebRequest.Create("https://www.google.com/recaptcha/api/siteverify?secret=" & secret_key & "&response=" & g_captcha_response)
request.Timeout = 5 * 1000 ' 5 Seconds to avoid getting locked up
request.Method = "POST"
request.ContentType = "application/json"
Try
Dim byteArray As Byte() = Encoding.UTF8.GetBytes("")
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As Net.WebResponse = request.GetResponse()
dataStream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
response.Close()
Return responseFromServer
Catch ex As Exception
Return "ERROR: " & ex.Message
End Try
End Function
Public Class ValidateResponse
Public Property success As Boolean
Public Property challenge_ts As DateTime
Public Property hostname As String
<JsonProperty("error-codes")>
Public Property error_codes As List(Of String)
End Class
End Class
End Class
So in the button's Click event, just call:
If Google.ReCaptcha.Validate(Request, Request.Url.Host) Then
' good to go
Else
' validation failed
End If

Getting web service response in SOAP on asp.net

I have set up a web service with an .asmx file and its web methods are being called via Ajax (all using asp.net scriptmanager etc) on the clientside.
When I call the webservice and look at the value of the return value in the callback, it is never in the 'SOAP' format, ie in xml. instead the value is returned in its raw form.
So for instance if I return a string from the webservice, the result passed to my successful callback is the string, not encoded or surrounded by XML tags.
How can I change this so I can see it in the SOAP format?
Are you calling from jquery? possible return in Json format. My guess without seeing your code.
It sounds like you are being returned the result of the web service function and letting .NET handle all of the underlying SOAP details. What you need to do if you want to see the HTTP SOAP response in your code, is instead of referencing the Web Service and invoking the function, issue an HTTP SOAP request. In VB.NET:
Dim _soapRequest As String = "<?xml version=""1.0"" encoding=""utf-8""?>" & _
"<soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">" & _
"<soap:Body>" & _
"<CelsiusToFahrenheit xmlns=""http://tempuri.org/"">" & _
"<Celsius>" & 100 & "</Celsius>" & _
"</CelsiusToFahrenheit>" & _
"</soap:Body>" & _
"</soap:Envelope>"
Dim response As String = DoRequestResponse(_soapRequest, "http://localhost:88/Service1.asmx")
and the DoRequestResponse Function looks like this
Public Function DoRequestResponse(ByVal _p_RequestString As String, ByVal _p_RequestURL As String) As String
Dim _httpWebRequest As HttpWebRequest
Dim _httpWebResponse As HttpWebResponse
Dim _streamReq As Stream
Dim _streamResp As Stream
Dim _streamReader As StreamReader
Dim _responseString As String
Dim _bytesToWrite() As Byte
Try
_httpWebRequest = CType(WebRequest.Create(_p_RequestURL), HttpWebRequest)
_httpWebRequest.Method = "POST"
_httpWebRequest.ContentType = "text/xml"
_httpWebRequest.Timeout = 30000
Dim EncodingType As System.Text.Encoding = System.Text.Encoding.UTF8
_bytesToWrite = EncodingType.GetBytes(_p_RequestString)
_streamReq = _httpWebRequest.GetRequestStream()
_streamReq.Write(_bytesToWrite, 0, _bytesToWrite.Length)
_streamReq.Close()
_httpWebResponse = DirectCast(_httpWebRequest.GetResponse(), HttpWebResponse)
_streamResp = _httpWebResponse.GetResponseStream()
_streamReader = New StreamReader(_streamResp)
_responseString = _streamReader.ReadToEnd()
_streamReader.Close()
_httpWebResponse.Close()
Catch ex As Exception
Dim _ex As WebException = ex
Console.Write(_ex.Status)
Console.Write(DirectCast(_ex.Response, HttpWebResponse).StatusCode)
Throw New Exception("DoRequestResponse Error :" & vbCrLf & ex.Message)
End Try
Return _responseString
End Function
You can do something like this in your code-behind of the asp.net page, and call it from AJAX, via postback, etc., which will then post to your .asmx web service and return the SOAP response.

Crystal Report convert to PDF (Error The logon to the database failed. ((0x8004100f)))

In my application I have some code to convert to PDF. In debug mode all is good and working but when I test it on then server I keep getting the logon to the database failed. I have no idea why I get the error becase the login and password are 100% ok.
tried 2 ways for the server of sending the report
SetCrystalReportFilePath(Server.MapPath("~/MemberPages/Report.rpt"))
SetPdfDestinationFilePath(Server.MapPath("~/MemberPages/Report_" & Report & ".pdf"))
SetRecordSelectionFormula("{Report.Report_id} =" & ID)
Transfer()
SetCrystalReportFilePath("C:\inetpub\wwwroot\Werkbon.rpt")
SetPdfDestinationFilePath("C:\inetpub\wwwroot\Werkbon_" & werkbonnr & ".pdf")
SetRecordSelectionFormula("{werkbon.werkbon_id} =" & werkbonnr)
Transfer()
Dim ConInfo As New CrystalDecisions.Shared.TableLogOnInfo
Dim oRDoc As New ReportDocument
Dim expo As New ExportOptions
Dim sRecSelFormula As String
Dim oDfDopt As New DiskFileDestinationOptions
Dim strCrystalReportFilePath As String
Dim strPdfFileDestinationPath As String
Public Function SetCrystalReportFilePath(ByVal CrystalReportFileNameFullPath As String)
strCrystalReportFilePath = CrystalReportFileNameFullPath
End Function
Public Function SetPdfDestinationFilePath(ByVal pdfFileNameFullPath As String)
strPdfFileDestinationPath = pdfFileNameFullPath
End Function
Public Function SetRecordSelectionFormula(ByVal recSelFormula As String)
sRecSelFormula = recSelFormula
End Function
Public Function Transfer()
oRDoc.Load(strCrystalReportFilePath)
oRDoc.RecordSelectionFormula = sRecSelFormula
oDfDopt.DiskFileName = strPdfFileDestinationPath
expo = oRDoc.ExportOptions
expo.ExportDestinationType = ExportDestinationType.DiskFile
expo.ExportFormatType = ExportFormatType.PortableDocFormat
expo.DestinationOptions = oDfDopt
oRDoc.SetDatabaseLogon("databasename", "password")
oRDoc.Export()
End Function
Crystal is very particular when swapping in and out connection information (especially with sub-reports if you have any). It's always been a sore spot that they haven't really made any better over the years. I have a blog entry I've shared that has extension methods I created (in VB.Net) to easily load and swap in new connections (typically I use ADO for the connection in the report). The extension methods can be found in this link (and below is an example of how to use them, ignore the System.Diagnostics line if you're using this from ASP.NET). Hope this helps.
http://www.blakepell.com/Blog/?p=487
Using rd As New ReportDocument
rd.Load("C:\Temp\CrystalReports\InternalAccountReport.rpt")
rd.ApplyNewServer("serverName or DSN", "databaseUsername", "databasePassword")
rd.ApplyParameters("AccountNumber=038PQRX922;", True)
rd.ExportToDisk(ExportFormatType.PortableDocFormat, "c:\temp\test.pdf")
rd.Close()
End Using
System.Diagnostics.Process.Start("c:\temp\test.pdf")

Upload files asynchronously with ASP.NET

I'm trying to make an asynchronous upload operation but I got this error message:
Error occurred, info=An exception
occurred during a WebClient request`.
Here's the upload function:
Private Sub UploadFile()
Dim uploads As HttpFileCollection
uploads = HttpContext.Current.Request.Files
Dim uri As Uri = New Uri("C:\UploadedUserFiles\")
Dim client = New WebClient
AddHandler client.UploadFileCompleted, AddressOf UploadFile_OnCompleted
For i As Integer = 0 To (uploads.Count - 1)
If (uploads(i).ContentLength > 0) Then
Dim c As String = System.IO.Path.GetFileName(uploads(i).FileName)
Try
client.UploadFileAsync(uri, c)
Catch Exp As Exception
End Try
End If
Next i
End Sub
Public Sub UploadFile_OnCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs)
Dim client As WebClient = CType(e.UserState, WebClient)
If (e.Cancelled) Then
labMessage.Text = "upload files was cancelled"
End If
If Not (e.Error Is Nothing) Then
labMessage.Text = "Error occured, info=" + e.Error.Message
Else
labMessage.Text = "File uploaded successfully"
End If
End Sub
Update 1:
Private Sub UploadFile()
Dim uploads As HttpFileCollection
Dim fileToUpload = "C:\Demo\dummy.doc"
Dim uri As Uri = New Uri("C:\UploadedUserFiles\")
Dim client = New WebClient
AddHandler client.UploadFileCompleted, AddressOf UploadFile_OnCompleted
client.UploadFileAsync(uri, fileToUpload)
End Sub
client.UploadFileAsync(uri, fileToUpload) is throwing this error message
Error occured, info=System.Net.WebException: The request was aborted: The request was canceled. at System.Net.FileWebRequest.EndGetResponse(IAsyncResult asyncResult) at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result) at System.Net.WebClient.DownloadBitsResponseCallback(IAsyncResult result)
By calling GetFileName you're truncating whatever path information was there. You should provide UploadFileAsync with a full path name.
Also, replace e.Error.Message with just e.Error so you get the full error details including inner exceptions. This will provide more info and probably lead you to the answer.
Dim uri As Uri = New Uri("C:\UploadedUserFiles\")
The above statement is wrong, how come you have Uri as a file system path, it should be "http://" or "https://" , if you are trying to upload it to your local asp.net web site project then you must have a url something like http://localhost:PORT/UploadedUserFiles ... and you will know port number when you execute project.
Dim uri As Uri = New Uri("http://localhost:PORT/Upload.aspx")
Try this:
1) Create a new class MyWebClient.
Class MyWebClient
Inherits WebClient
Protected Overrides Function GetWebRequest(address As Uri) As WebRequest
Dim req = MyBase.GetWebRequest(address)
Dim httpReq = TryCast(req, HttpWebRequest)
If httpReq IsNot Nothing Then
httpReq.KeepAlive = False
End If
Return req
End Function
End Class
2) Use this class instead of the default WebRequest.
Private Sub UploadFile()
Dim uploads As HttpFileCollection
uploads = HttpContext.Current.Request.Files
Dim uri As Uri = New Uri("C:\UploadedUserFiles\")
Dim client = New MyWebClient
AddHandler ...
I hope this helps.
From the reference to HttpContext.Current.Request.Files I am assuming that your are running the code in a web project. You don't have to use WebClient to save the file to your disk. All you have to do is this:
Private Sub UploadFile()
Dim uploads As HttpFileCollection
uploads = HttpContext.Current.Request.Files
Dim path As String = "C:\UploadedUserFiles\"
For i As Integer = 0 To (uploads.Count - 1)
If (uploads(i).ContentLength > 0) Then
Dim p As String = System.IO.Path.Combine(path, System.IO.Path.GetFileName(uploads(i).FileName))
uploads(i).SaveAs(p)
End If
Next i
End Sub
I'm not that good with VB.. so there might be syntax problems :) bear with me..
You can't upload files from the ASP.NET web request asyncronously via this mechanism. The file is actually in the body of the http request so it is already on the server. Request.Files provides a stream to the files that are already on the server.
You could use something like Silverlight or Flash from the client side.
You might want to investigate the AJAX Control Toolkit and use the AsyncFileUpload control.
The control has a server side event when upload is complete. (UploadedComplete)
It also has a SaveAs(string filename) method for the uploaded file.
Simple Usage:
Markup
<asp:AsyncFileUpload ID="upload" runat="server" OnUploadedComplete="displayFile"/>
Code Behind
protected void displayFile(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
upload.SaveAs("C:\\text.txt");//server needs permission
}
Try to add Header information to the WebClient Object as below :
With webClient
.Headers.Add("Content-Type", Web.MimeMapping.GetMimeMapping("C:\filename.txt"))
.Headers.Add("Keep-Alive", "true")
.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)")
.Credentials = New Net.NetworkCredential("UserName", "password")
End With

Resources