How to upload files to http directory in vb.net - vb.net

I have a windows forms application in VB.Net, and I am trying to upload a photo to a local http address http://10.0.0.13/MyStorageDevice/.
When opening this address from my browser it requests a username and a password. I can then log in with the correct username and password, and it shows list of all files uploaded to this path.
I tried to use WebClient.UploadFile but its not working. I read all the details in the msdn documentation here:
https://msdn.microsoft.com/en-us/library/36s52zhs(v=vs.110).aspx
Whats the wrong here ?
Dim uriString As String = "http://10.0.0.13/MyStorageDevice/"
' Create a new WebClient instance.
Dim myWebClient As New WebClient()
myWebClient.Headers.Add("Content-Type", "application/octet-stream")
myWebClient.Credentials = New NetworkCredential("UserName", "Password")
' Upload the file to the URI.
' The 'UploadFile(uriString,fileName)' method implicitly uses HTTP POST method.
Dim responseArray As Byte() = myWebClient.UploadFile(uriString, "C:\Users\areej\Pictures\pic1.png")
The code throws this exception:
System.Net.WebException: The remote server returned an error: (405)
Method Not Allowed. at System.Net.WebClient.UploadFile(Uri address,
String method, String fileName) at
System.Net.WebClient.UploadFile(String address, String fileName)
How can I fix this?

Related

Download Image From WebServer (cPanel/VPS) in VB.NET

I'm trying to make a function to download images from a server and use them in a picturebox and if needed save it locally. Right now I'm using:
Public Function WebImgDownload(ByVal Url As String, Optional ByVal saveFile As Boolean = False, Optional ByVal location As String = "C:\") As Image
Dim client As New WebClient With {
.Credentials = New NetworkCredential("username", "password")}
Dim bytes() As Byte = client.DownloadData(Url)
Dim stream As New IO.MemoryStream(bytes)
If saveFile Then My.Computer.FileSystem.WriteAllBytes(location, bytes, False)
Return New Bitmap(stream)
End Function
Now this all works fine when I use the function like:
PictureBox1.Image = WebImgDownload("myurl")
But it only works when I provide world permissions to the folder on cPanel. If I only provide user permission to the folder so it will require authentication and use my credentials it responds with a 404 error message.
I'm using the user and password I login to the server but it just throws the error:
System.Net.WebException: 'The remote server returned an error: (404) Not Found.'
Is there something I'm missing?
Thanks in advance!
So I found my error. I was trying to authenticate by just using the normal address when I needed to use the ftp address for the file. In my case I was using:
https://myserver/folder/file.jpg
Now instead I used the ftp address like this:
ftp://myserver/public_html/folder/file.jpg
That way it authenticates correctly and points to the file correctly too because not using the public_html in the address was pointing it to the wrong folder.
For some reason when you dont need to authenticate with the server you can just use the normal address when the file is public.

JIRA - pass credentials for a webrequest to API?

Trying to build a service that will grab info on a JIRA ticket based on an ID passed to it.
I'm calling the API to take the ID passed to the service, tack it onto the URL for the API and get the JSON object.
Problem is, it appears one must be logged on or registered on JIRA in order to use the API.
So if I use the code below to make my request, I get a 404 error, as I do on any browser which I've not used to log onto Jira
public string Get(string id)
{
string html = string.Empty;
string url = #"https://company.atlassian.net/rest/api/latest/issue/" + id;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
html = reader.ReadToEnd();
}
return html;
}
I can add credentials to the request like so
request.Credentials = new NetworkCredential("vinnie#company.com","mypassword");
but I've no idea exactly what needs sending. I've tried the email address with which I'm set up in Jira but that doesn't work.
I have a suspicion that Jira adds a cookie to my browser which it uses to validate after the initial config - is that so? If so, what can I add/include on my web request to get it to run?
Am I just wildly off on the right way to access it? Or are there changes that can be made to the Jira side to allow requests?
You have to encode your credentials in Base64 format first and then these credentials can be put into your request as shown below:
string mergedCredentials = string.Format("{0}:{1}", m_Username, m_Password);
byte[] byteCredentials = UTF8Encoding.UTF8.GetBytes(mergedCredentials);
string base64Credentials = Convert.ToBase64String(byteCredentials);
request.Headers.Add("Authorization", "Basic " + base64Credentials);
Hope you're able to solve your problem by this approach!

Why Does my Service Account Attempt to Connect to Google API via OAuth2 Return an 'invalid_grant' error?

I am attempting to use a Service Account to talk to the Admin SDK Directory API via the .Net Client Library. However, the response I keep getting is a 400 Bad Request with a json response content of "error":"invalid_grant".
Here is my code
Public Sub New()
Dim _certificate = New X509Certificate2("c:\path\to\file.psk", "notasecret" _
, X509KeyStorageFlags.Exportable)
Dim _serviceAccountEmail = "email#developer.gserviceaccount.com"
Dim _scopes As IList(Of String) = New List(Of String)()
_scopes.Add(directory_v1.DirectoryService.Scope.AdminDirectoryUserReadonly)
Dim credential = New ServiceAccountCredential(New
ServiceAccountCredential.Initializer(_serviceAccountEmail) With {
.Scopes = _scopes}.FromCertificate(_certificate))
Dim service = New directory_v1.DirectoryService(New BaseClientService.Initializer() With { _
.HttpClientInitializer = credential,
.ApplicationName = "AeriesConnect"})
Dim request = service.Users.List()
request.Domain = "my.domain.com"
Dim users As directory_v1.Data.Users = request.Execute()
For Each user In users.UsersValue
System.Diagnostics.Debug.WriteLine("userName ID: " & user.Id)
Next
End Sub
Service Object
My service object has the following properties. All other properties are empty collections of the UsersResource or GroupsResource
service.BaseUri = 'https://www.googleapis.com/admin/directory/v1"
service.HttpClientInitializer Properties
Notice that the Token property is empty. Does that matter? It seems like it does. Is that my fault?
Request Object
I get the error right at the Execute and the exception is from Google and is a Google.Apis.Auth.OAuth2.Responses.TokenResponseException.
I think I've granted all the permissions I need to BUT keep in mind, this is for a Google Apps for Education account.
Logging in as a Super User to the Developer Console, I've created a project and enabled the Admin SDK API. I've also created the Credentials.
As a 'Super User' in that GAFE, I've gone to the "Security --> Advanced Settings --> Manage API Client Access" area and added my Client ID (not email) and the scope as https://www.googleapis.com/auth/admin.directory.user
Request Header
My request header that is POST to https://accounts.google.com/o/oauth2/token has this
assertion=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6Imh0dHBzOi8vd3d3L
mdvb2dsZWFwaXMuY29tL2F1dGgvYWRtaW4uZGlyZWN0b3J5LnVzZXIiLCJpc3MiOiI2OTY3MTQyNzg2OS1hb
XFmMjVzY204Y2N1azhycHJrMDQ2djAzb2cybGducEBkZXZlbG9wZXIuZ3NlcnZpY2VhY2NvdW50LmNvbSAiLC
JhdWQiOiJodHRwczovL2FjY291bnRzLmdvb2dsZS5jb20vby9vYXV0aDIvdG9rZW4iLCJleHAiOjE0MTQ2MTY
3NDMsImlhdCI6MTQxNDYxMzE0M30.T9H-3tgOQSNdSj3MrUjJNNR5YqsxuJ97bCMJrrEJQ1Noewyv2mj
Dp96AZSZmzSxseAWrgptUv7sR4Mi21CWNACmjQjWPw8BI48sAyIclUPq6UhtMhRZDB1xX7t-Tq8NSbddJt
yJWxTc-IEAT7ixVpjjrosdG8Zcs0MgTuUgKHb8
&grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer
...and the last bits of it feel wrong. Why does it feel like it suddenly has been HTML encoded?
Question
What have I done wrong? I'm assuming it think's I'm not authenticated. But what do I need to do differently? I've used their examples to help, but I can't quite figure it out.
My problem was that I had the wrong value in the Service Account Email field. Simple solution. Took me two days to figure it out. Ugh!

How to download a image from a protected link

How to download a image from a protected below link http://epaper.manoramaonline.com/MMDaily/Malappuram/2014/05/30/F/MMDaily_Malappuram_2014_05_30_F_FP_001/1228_274_1940_1862.jpg
while I downloading this jpeg file the following error was display " the remote server returned an error (403) forbidden". Please help me to find a solution.
The following code was used..
My.Computer.Network.DownloadFile("http://epaper.manoramaonline.com/MMDaily/Malappuram/2014/05/30/F/MMDaily_Malappuram_2014_05_30_F_FP_001/1228_274_1940_1862.jpg", "D:/ynews.jpg")
You might need to specify the network credential to bypass the authorization and authentication. I can give you an example of C# Code of the same. You check the same with VB.Net and try to resolve.
WebClient webClient = new WebClient();
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(webClient_DownloadFileCompleted);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
webClient.Credentials = new NetworkCredential("user", "pass");
webClient.DownloadFileAsync(new Uri("http://example.com/example.jpg"), #"c:\myfile.txt");

Calling SharePoint Web Service over SSL in VB.Net (401 Unauthorized)

I'm trying to call the AddAttachment of the Lists.asmx SharePoint web service the below code works fine if I'm calling the web service over HTTP.
Dim img(MyFile.PostedFile.ContentLength - 1) As Byte
MyFile.PostedFile.InputStream.Read(img, 0, img.Length)
'Dim fStream As FileStream = File.OpenRead(FullFileName)
Dim fileName As String = MyFile.PostedFile.FileName.Substring(3)
Dim listService As New wsList.Lists()
Dim credentials As New System.Net.NetworkCredential(UserName, Password, Domain)
If Not SiteUrl.EndsWith("/") Then
SiteUrl += "/"
End If
SiteUrl += "_vti_bin/Lists.asmx"
'SiteUrl = SiteUrl.ToLower.Replace("http:", "https:")
listService.Url = SiteUrl
listService.Credentials = credentials
Dim addAttach As String = listService.AddAttachment(ListName, ItemId, fileName, img)
ReturnValue = True
However if I uncomment out this line
'SiteUrl = SiteUrl.ToLower.Replace("http:", "https:")
I will get the following error: The request failed with HTTP status 401: Unauthorized
Now if I leave the above line commented out AND then also comment out this line
listService.Credentials = credentials
I will get the same 401 error (expected) so it appears the credentials are being accepted correctly over HTTP but not HTTPS. Can one help explain this to me and have any thoughts on how to fix the issue?
Thanks in advance!
This morning I was working with one of our system guys. He checked some IIS logs and could see errors trying to access the web service over HTTPS. He went into Central Admin and added some Alternate Access Mappings to include the HTTPS urls. Then everything worked!