Exchange Web Services API 1.0 Error - exchange-server

I'm getting the following error when trying to connect to my exchange server at Microsoft Online. I couldn't see how to get access to the underlying XML and I wondered if this error is caused because exchange is just serving the standard OWA login form, rather than an XML response that the EWS API expects. How can I check this?
This is the error, thrown on the the last line of my code:
'>' is an unexpected token. The expected token is '"' or '''. Line 7, position 62.
This is my code:
Dim ews As New ExchangeService
ews.Credentials = New WebCredentials("mytestmailbox#mydomain.com", "mypassword")
ews.Url = New Uri("https://mysubdomain.microsoftonline.com")
'send a test message
Dim message As New EmailMessage(ews)
message.Subject = "Hello World!"
message.Body = "This is a test message"
message.ToRecipients.Add("some#email.com")
message.SendAndSaveCopy()

I fixed this by changing the Uri to the following: https://servername/ews/Exchange.asmx

Related

msxml6.dll error '800c0005' The system cannot locate the resource specified [duplicate]

I have a function which uses MSXML to post an XML document which yesterday started failing despite no change being made to the code. The function is as follows:
Public Function PostFile(ByVal address As String, ByVal data As Byte()) As xmldocument
Dim xmlHTTP As New MSXML2.XMLHTTP
Dim response As New XmlDocument
Dim xmlDoc As New MSXML2.DOMDocument
Try
xmlDoc.load(data)
xmlHTTP.open("post", address, False)
xmlHTTP.send(xmlDoc)
If xmlHTTP.responseXML.xml <> String.Empty Then
response.LoadXml(xmlHTTP.responseXML.xml)
Return response
Else
Dim result As String = "<NO_Response><Error>the post succeeded to " + address + " but there was no responce returned</Error><Hint>Check FireWall Settings</Hint></NO_Response>"
response.loadxml(result)
Return response
End If
Catch ex As Exception
'Error logging code removed
End Try
Return Nothing
End Function
The XML document and the address being passed in are both correct - the line which causes the error is xmlHTTP.send(xmlDoc). I have tried this on 2 different machines with the same error each time and have also tried resinstalling MSXML3, with no success.
The exception thrown is:
InnerException: Nothing
Message: "The system cannot locate the resource specified. "
Source: "msxml3.dll"
StackTrace: " at MSXML2.XMLHTTPClass.send(Object varBody) at comms.HTTPHandler.PostFile(String address, Byte[] data) in D:\SCC\Main\Sender\Http.vb:line 42"
It turned out to be a networking issue - I didn't suspect this at first as the error was raised so quickly which didn't suggest an issue with the endpoint. The problem was with a rule which had been added (don't ask why) to the firewall preventing communication with the destination address.
If you are just processing the xml or dtd is offline, you can use:
xmlDoc.resolveExternals = False

Sending an email with ruby gmail api v0.9

Does anyone have a simple example as to how to send an email from scratch with the v0.9 API.
simply want an example of sending the following:
m = Mail.new(
to: "test1#test.com",
from: "test2#test.com",
subject: "Test Subject",
body:"Test Body")
Now to create that message object which is required to send,we can use:
msg = Base64.urlsafe_encode64 m.to_s
And then try to send (where message_object = msg):
client = Google::Apis::GmailV1::GmailService.new #Appropriately authorised
client.send_user_message("me", message_object)
The client wants an RFC822 compatible encoded string, which the above should be.
I've tried:
message_object = msg
=> Google::Apis::ClientError: invalidArgument: 'raw' RFC822 payload message string or uploading message via /upload/* URL required
message_object = raw:msg
=>ArgumentError: unknown keyword: raw
message_object = {raw:msg}
=>ArgumentError: unknown keyword: raw
message_object = Google::Apis::GmailV1::Message.new(raw:msg)
=> #<Google::Apis::GmailV1::Message:0x007f9158e5b4b0 #id="15800cd7178d69a4", #thread_id="15800cd7178d69a4">
#But then I get Bounce <nobody#gmail.com> - An error occurred. Your message was not sent.
i.e. None of them work...
Sending the basic encded string (msg above) through the Gmail API interface tester here works.
I'm obviously missing something obvious here as to how to construct that object required to make it work through the API.
Ok. So the answer... thanks for all your help Holger...
Was that the documentation is wrong. It asks you to encode to base64.
The base64 encoding is not required (it is done internally by the api client).
The correct way to send is
msg = m.encoded
# or m.to_s
# this doesn't base64 encode. It just turns the Mail::Message object into an appropriate string.
message_object = Google::Apis::GmailV1::Message.new(raw:m.to_s)
client.send_user_message("me", message_object)
Hope that saves someone else from being patronised by an overzealous mod.
Carpela‘s answer works fine, but for the message_object, it's missing "raw" in Message.new. The correct code should as following:
message_object = Google::Apis::GmailV1::Message.new(raw: m.encoded) # or m.to_s
client.send_user_message('me', message_object)

What are the AppName, AppPublisher and AppVersion header values for a WSE 2012 R2 WebApi call?

I'm trying to query my Server 2012 Essentials R2 server to determine the most recent Client Backup time for a given Device, so I can display nag screens at signon for forgetful users. (They're on laptops, so I can't depend on the machine being available during the automatic window.)
The closest thing in the way of documentation I've been able to find is this: (https://msdn.microsoft.com/en-us/library/jj713757.aspx)
GET services/builtin/DeviceManagement.svc/devices/index/{index}/count/{count}
But it requires a preceding call to get the token: (https://msdn.microsoft.com/en-us/library/jj713753.aspx)
GET https://www.contoso.com/services/builtin/session.svc/login HTTP/1.1
Accept: application/xml
Host: servername
Authorization: Basic VXNlcjpQYXNzd29yZCE=
AppName: Sample App Name
AppPublisher: publisher
AppVersion: 1.0
Does anyone know what the values for those last three headers should be—or how to discover them—for a standard WSE 2012 R2 installation? The documentation provides no assistance here.
Or if someone knows a better way to accomplish this, please let me know.
OK, I got it working. The code is below.
As it turns out, the value of the AppName header is irrelevant—it can be any string, but it can't be empty.
I already knew it couldn't be empty from a look at the WSE source in Wssg.WebApi.Framework in the GAC, but the code is decoupled to the point that it's next to impossible to find out what process picks up the the RemoteConnectionClientInfo object once it gets dropped into the HTTP session.
The part that was misleading me was—go figure—the documentation itself.
There's a bang (!) after the password on the Authentication page, suggesting that it should trail the actual password prior to encoding. This was why I was getting an authentication error, which in turn I was (mistakenly) attributing to the statement in the documentation: "Add Appname, Apppublisher, and Appversion values in HTTP header fields. These values are also required to log on."
So once I cleared all that up, I sailed right in.
And there are other errors in the documentation. On the Devices page we are told that the Host header should be set to the domain name, and that a Content-Length header should be added.
These are both incorrect. The Host header should be the server's hostname and there should be no Content-Length header (that's a response header, not a request header).
AND...! After all this, I find that the Device info returned doesn't contain the most recent backup time. I'll have to dig further for that. But at least now I can connect.
So Microsoft's incomplete, inaccurate and sloppy documentation has cost me a day's work. Hopefully somebody else can use this and avoid the pain I went through.
Module Main
Public Sub Main()
Dim aCredentials() As Byte
Dim _
oAuthenticateUri,
oDeviceListUri As Uri
Dim _
sCanary,
sCookie,
sDevices As String
aCredentials = Encoding.ASCII.GetBytes($"{USERNAME}:{PASSWORD}")
Using oClient As New HttpClient
oAuthenticateUri = New Uri($"https://{HOST}/services/builtin/session.svc/login")
oDeviceListUri = New Uri($"https://{HOST}/services/builtin/devicemanagement.svc/devices/index/0/count/99")
oClient.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/xml"))
oClient.DefaultRequestHeaders.Authorization = New AuthenticationHeaderValue("Basic", Convert.ToBase64String(aCredentials))
oClient.DefaultRequestHeaders.Host = HOST
oClient.DefaultRequestHeaders.Add("AppPublisher", String.Empty)
oClient.DefaultRequestHeaders.Add("AppVersion", String.Empty)
oClient.DefaultRequestHeaders.Add("AppName", "None")
Using oAuthenticateResponse As HttpResponseMessage = oClient.GetAsync(oAuthenticateUri).Result
If oAuthenticateResponse.IsSuccessStatusCode Then
sCanary = oAuthenticateResponse.Headers.Single(Function(Pair) Pair.Key = CANARY_HEADER).Value(0)
sCookie = Split(oAuthenticateResponse.Headers.Single(Function(Pair) Pair.Key = COOKIE_HEADER).Value(0), ";")(0)
oClient.DefaultRequestHeaders.Clear()
oClient.DefaultRequestHeaders.Host = HOST
oClient.DefaultRequestHeaders.Add(CANARY_HEADER, sCanary)
oClient.DefaultRequestHeaders.Add(COOKIE_HEADER, sCookie)
Using oDeviceListResponse As HttpResponseMessage = oClient.GetAsync(oDeviceListUri).Result
If oDeviceListResponse.IsSuccessStatusCode Then
sDevices = oDeviceListResponse.Content.ReadAsStringAsync.Result
Else
Console.WriteLine("{0} ({1})", oDeviceListResponse.StatusCode, oDeviceListResponse.ReasonPhrase)
End If
End Using
Else
Console.WriteLine("{0} ({1})", oAuthenticateResponse.StatusCode, oAuthenticateResponse.ReasonPhrase)
End If
End Using
End Using
End Sub
Private Const CANARY_HEADER As String = "Canary"
Private Const COOKIE_HEADER As String = "Set-Cookie"
Private Const USERNAME As String = "domain.admin"
Private Const PASSWORD As String = "admin.password"
Private Const HOST As String = "server"
End Module

Send gmail messages with google-api-ruby-client '0.9.pre3'

Working through sending gmail with the newer google-api-ruby-client in a rails 4 application.
require 'google/apis/gmail_v1'
Gmail = Google::Apis::GmailV1
class MailService
def initialize(params)
#params = params
end
def call
message = Gmail::Message.new
service = Gmail::GmailService.new
message.raw = (redacted)
service.request_options.authorization = current_user.token.fresh_token
result = service.send_user_message(current_user.email, message)
end
end
And this is the result from the call to the API:
Sending HTTP post https://www.googleapis.com/gmail/v1/users/me/messages/send?
200
#<Hurley::Response POST https://www.googleapis.com/gmail/v1/users/me/messages/send == 200 (63 bytes) 858ms>
Success - #<Google::Apis::GmailV1::Message:0x007fc9cf9b52dd
#id="15096369c05cdb1d",
#thread_id="15096369c05cdb1d">
The raw message sends without issue from the API explorer but when executed from my application I get a bounce email in my inbox. In the above example the redacted sample is a valid RFC 2822 formatted base-64 url safe string and fresh_token represents the oauth2 access token for the current user.
A look at the bounced mail
Bounce <nobody#gmail.com>
2:43 PM (19 minutes ago)
to me
An error occurred. Your message was not sent.
Anyone have any thoughts? It seems like perhaps my (sender) email is being picked up in the raw message but not the recipient... Though I suppose the API could be forwarding the bounce based on my oauth access token.
I very much appreciate any help. Thanks!
EDIT: Solution was to pass the RFC 2822 string as raw property without base64 encoding.
Steve Bazyl seems to be correct. The documentation on send_user_message is wrong as of (0.9.13). For raw, it says: "The entire email message in an RFC 2822 formatted and base64url encoded string. Returned in messages.get and drafts.get responses when the format=RAW parameter is supplied. Corresponds to the JSON property raw." As far as I can tell, this is simply incorrect.
I encountered this issue when updating from google-api-client 0.8 to 0.9 and removing the base64 encoding solved the problem. I.e. call in 0.8:
response = #service.execute(
api_method: api.users.messages.to_h['gmail.users.messages.send'],
body_object: {
raw: Base64.urlsafe_encode64(mail.to_s)
},
parameters: {
userId: 'me',
}
)
became
message = { raw: mail.to_s }
res = #service.send_user_message('me', message, {})
in 0.9.
Reported as https://github.com/google/google-api-ruby-client/issues/474.

Google oauth2 error "Required parameter is missing: response_type" (Ruby)

My first Ruby adventure is to try and get oauth2 token for web service app from google. There are many questions and answers on this topic, but none that resolved my issue.
I registered a dummy web service with google and am trying to get authorization code (even before trying to get a token). Doesn't matter what mandatory parameter I omit (e.g. client_id) when accessing https://accounts.google.com/o/oauth2/auth I always get 400 error with message 'Required parameter is missing: response_type'.
Here is the code snippet, following Google's guidelines in https://developers.google.com/accounts/docs/OAuth2WebServer#formingtheurl:
get '/' do
requestGoogleAccessToken(102030, "http://localhost:4567/oauth2callback/")
end
def requestGoogleAccessToken(auth_code, redirect_uri)
googleAuthHost = 'https://accounts.google.com/o/oauth2/auth'
googleClientID = "XXXXXXXXXXX.apps.googleusercontent.com"
scope = 'https://www.googleapis.com/auth/calendar'
url="#{googleAuthHost}?scope=profile&redirect_uri=#{CGI.escape(redirect_uri)}&client_id=#{googleClientID}&response_type=code"
uri=URI.parse(url)
https=Net::HTTP.new(uri.host,uri.port)
https.use_ssl=true
req=Net::HTTP::Post.new(uri.path)
res=https.request(req)
puts "\n res: ", res
puts "\n response body: ", res.body
end
Thanks in advance for your help.

Resources