How to download a image from a protected link - vb.net

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");

Related

Use RestSharp to get MS Graph token

I am new to using MS Graph and the new version of RestSharp. I put together a simple console app in VB.NET to learn the process. Have spent way too much time looking at solutions on the internet, but not getting the answers I want. The ultimate goal is to upload files to a OneDrive account autonomously.
So I created an App registration on Azure for this app. Then to test I created a console app to test how the process works. I am using the latest version of RestSharp which is very different from the version I was using. The console app calls a simple subroutine shown below to get the token to make calls to Graph. When I run I get the errors: "System.Net.ProtocolViolationException' in System.dll" and "System.Net.ProtocolViolationException' in mscorlib.dll". Code follows:
Dim client As New RestClient("https://login.microsoftonline.com/f8cde-----/oauth2/v2.0/token")
Dim request As New RestRequest(Method.Post)
request.AddHeader("Content-Type", "application/x-www-form-urlencoded")
request.AddHeader("Host", "login.microsoftonline.com")
Dim body As String = "client_id=8e4---------" &
"scope=api://8e4da056-8425-4-.default" &
"client_secret=Piy7Q~7----------" &
"grant_type=client_credentials"
request.AddBody(body)
Dim response As RestSharp.RestResponse = Await client.ExecuteAsync(request)
Console.Write(response.Content.ToString)
Console.ReadKey()
End Sub
I admit I really don't know what I am doing here, but want to learn.
I can suggest spending time reading the documentation. RestSharp forms the request correctly if you use the RestRequest API to build the request.
Here is what you need to do:
Dim options = New RestClientOptions("https://login.microsoftonline.com/f8cde-----/oauth2/v2.0/token")
options.BaseHost = "login.microsoftonline.com"
Dim client = New RestClient(options)
Dim request As New RestRequest(Method.Post)
request.AddParameter("client_id", "8e4---------")
request.AddParameter("client_secret", "Piy7Q~7----------")
request.AddParameter("grant_type", "client_credentials")
Dim response = Await client.ExecuteAsync(request)

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.

How to upload files to http directory in 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?

How to upload a new file to OneDrive using new API?

I'm trying to get file uploads working with the new OneDrive API. I'm starting out with just simple files (i.e. < 100MB) with the intention of progressing to resumable uploads once I've got the simple ones working!
I've tried using http://onedrive.github.io/items/upload_put.htm but I'm getting 403 back. I thought that this might be because the file didn't already exist but I've uploaded the file using the OneDrive web UI successfully and the code still can't upload the file.
The URL I'm using is something like:
https://api.onedrive.com/v1.0/drive/root:/:/content?access_token=
The C# code is:
using (Stream fileStream = await file.OpenStreamForReadAsync())
{
try
{
HttpStreamContent streamContent = new HttpStreamContent(fileStream.AsInputStream());
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, oneDriveURI);
request.Content = streamContent;
request.Content.Headers.ContentType = new Windows.Web.Http.Headers.HttpMediaTypeHeaderValue("application/octet-stream");
HttpResponseMessage response = await client.SendRequestAsync(request);
Debug.WriteLine("UploadFileToOneDrive: response = {0}", response.StatusCode);
}
catch (Exception ex)
{
Debug.WriteLine("UploadFileToOneDrive failed with exception {0}", ex.Message);
}
}
What have I got wrong/misunderstood? The API documentation needs a LOT more examples :-(
403 error code is related to permissions so it could be possible that you may have forgotten to include the proper scopes to upload the file. When you send your OAuth request, you'll want to also include "onedrive.readwrite" as one of the scopes.
GET https://login.live.com/oauth20_authorize.srf?client_id={client_id}&scope={scope}&response_type=token&redirect_uri={redirect_uri}
More scopes can be found at "http://onedrive.github.io/auth/msa_oauth.htm". I hope that helps.

Error using FTPWebRequest on IIS7.5 and .NET 4.0

I have a simple class in an ASP.NET webservice. It runs fine on my local system and even on the development environment I've set up, but Anytime I try to send a file on the production server I get the following error:
Exception Error: The underlying provider failed on Open.
Here is the code that is being called:
public class FTPHelper
{
public static string SendFile(string ftpuri, string username, string password, string ftppath, string filename, byte[] datatosend)
{
if (ftppath.Substring(ftppath.Length - 1) != "/")
{
ftppath += "/";
}
FtpWebRequest ftp = (FtpWebRequest) FtpWebRequest.Create( ftpuri + ftppath + filename);
ftp.Method = WebRequestMethods.Ftp.UploadFile;
ftp.Credentials = new NetworkCredential(username, password);
ftp.UsePassive = true;
ftp.ContentLength = datatosend.Length;
Stream requestStream = ftp.GetRequestStream();
requestStream.Write(datatosend, 0, datatosend.Length);
requestStream.Close();
FtpWebResponse ftpresponse = (FtpWebResponse)ftp.GetResponse();
return ftpresponse.StatusDescription;
}
}
How can I troubleshoot this issue. The Server is IIS 7.5 running on Windows 2008 Server. I'm using .NET 4.0. Is there a simple reason why the FtpWebResponse would not be working?
If it's a security issue, then is there any way around it? I need to get this working immediately.
It was a security issue, the user that the website was running as did not have permission to establish the FTP connection. I am a programmer and not a web site administrator, so I did not have a clue how to accomplish this. After searching through Microsoft's IIS help on IIS, finally worked my way through it. The solution to change the user is on SuperUser:
https://superuser.com/q/307168/68967
If anyone has any better solutions, please respond. If anyone feels this would open up security issues, also, please post more information.