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

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!

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.

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?

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!

HTTPS webservice using WCF

I try to connect to https web service over proxy at my end.
below is code snippet
Dim strProxyURL As String = "http://myproxy.com"
Dim mypingRequest As New pingRequest()
Dim httpUri As New Uri("https://mysite.com")
Dim mybinding As New WSHttpBinding()
Dim remoteAddress As New EndpointAddress(httpUri)
mybinding.UseDefaultWebProxy = True
mybinding.BypassProxyOnLocal = True
mybinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.Windows
mybinding.MessageEncoding = WSMessageEncoding.Mtom
mybinding.TextEncoding = System.Text.Encoding.UTF8
mybinding.Security.Mode = SecurityMode.TransportWithMessageCredential 'TransportWithMessageCredential
mybinding.Security.Message.ClientCredentialType = MessageCredentialType.Windows
Dim myMBClient As New v1_PortTypeClient(mybinding, remoteAddress)
myMBClient.ClientCredentials.Windows.ClientCredential.UserName = "username"
myMBClient.ClientCredentials.Windows.ClientCredential.Password = "pwd"
myMBClient.ping()
when I use proxy I error proxy authentication required error
if I remove proxy from desktop and use direct internet then I go to site web service but cannot login even thought the gave correct username and password
issue is resolved. WCF web services uses Custom binding hence error. also i have add webrequest.defaultwebproxy and credentials to access via web proxy at requesting client side WCF Custom Http Proxy Authentication

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.