OutlookServicesClient throws a DataServiceQueryException - c#

When trying to execute a request using Microsoft.Office365.OutlookServices OutlookServicesClent with query, returns with Microsoft.OData.Client.DataServiceQueryException
Stack trace:
at Microsoft.OData.Client.DataServiceContext.InnerSynchExecute[TElement](Uri requestUri, String httpMethod, Nullable1 singleResult, OperationParameter[] operationParameters)
at Microsoft.OData.Client.DataServiceRequest.Execute[TElement](DataServiceContext context, QueryComponents queryComponents)
at Microsoft.OData.Client.DataServiceContext.Execute[TElement](Uri requestUri, String httpMethod, OperationParameter[] operationParameters)
at BL.OutlookAnalysisService.GetListOfMessagesByQuery(OutlookServicesClient service, Uri searchUri
and the error is:
Microsoft.OData.Client.DataServiceQueryException)exception).Response.Error"{\"error\":{\"code\":\"ErrorServiceUnavailable\",\"message\":\"Active Directory operation did not succeed. Try again later.\"}}"
System.Exception {Microsoft.OData.Client.DataServiceClientException}
Update
http request:
`GET /api/v2.0/me/mailfolders/SentItems/messages?$filter=ReceivedDateTime%20ge%202016-11-22 HTTP/1.1
OData-MaxVersion: 4.0
Accept: application/json;odata.metadata=minimal
Accept-Charset: UTF-8
User-Agent: Microsoft ADO.NET Data Services
Authorization: Bearer EwAYA+l3BAAUWm1xSeJRIJK6txKjBez4GzapzqMAAfh6O0QoQEsdN6OkFbuNKi/TXNzqUKWObaTUhPeziD3SYgEvHNGDxcvME0+Tt0/L8pWBlOSkeaKEYgd3B7C7go+8pDVQGeBoHhLhrmp4zMbtbdOiDJcxRwaUJ36Ak4DpCV665COyP2tS5/zbbq9+EIBFg0TQWbdOjMqN12DJGvRR+TzgMwWDV3IE1sJzAOi5CzYM7oy1pS1JX7JBq8ZxB7+kI1tjksanXymLZ5mlRRJp+XoR73mBocIgljLRPFaovyzUzMsEuTAvZ1gbbYqqH0u+hXNrlDDsFKtKeXb8IWGYeud+WMGmZbatt4LTZTXmBFYJf9hYZdaKNBQkBbvnc4IDZgAACHKN9ak8g6O86AHAhJwa9lFr9IgY4SPRdmUHqYDC4TSr8R+RVsANy4RSFe/p90sdRZXwvFsQ4JioWsVtQ0J3Aoh9cVNOKgZg2SIqm2Ni8VHD/EXSqtZqu0KZCKFSRrRxUSdzr3oG98hhbo1DcykWWyiI9PuPBxkFT60ZjC8+1NyXiX64vDOAQ9jvNf4BpGiahfDuzWajmeDiPXMd25ohXeY6s4XX5XhWDWXrDA5CdU+n1ZyF4kzUtCvalWTCIqRQ0UOXmEqa1nWNFIC0Vb6gTZl3HJqkRZxY9X+V0qHJYZyr5Ynss+FajWxnoYqasNNGZDWlJmBeAlIcWHO4kd8ggBiBBZdl7+unO1+jJhenRV2sSFGx11DQPOzRC3DvqwMwr0iJ9ZJ6vMUrAmvT1M3+0fyXEJsvfnz043oSgjPnQbihmtvlqIKO4M3kp3uKaRU2XOGhID9nsS31YefVDgThBzGLstRmj7jaMVbUQKkIZ0WYWIdp9uHEYWHlq0bvyvBqULmQMXAXczOuYaKAfOZqZX+FDaBYF6+BkGVtJ233sd7NwM8kInYnbLgtjAgyS9lxcqCCR2Kax6yhwBRFtNbV1F9+w4CC7K+EDelp8KGQUEA65MLwkZaO28rjagU3ps+uiAVr+IhsBO4XUVmCBpjIO6y1SxYC
X-ClientService-ClientTag: Office 365 API Tools 1.0.33.0
X-AnchorMailbox: outlook_F26A78076F4A0070#outlook.com
Host: outlook.office.com`
http response:
`HTTP/1.1 503 Service Unavailable
Content-Length: 0
Server: Microsoft-IIS/8.5
request-id: f1eec46a-9e69-426e-8013-a321b32b6916
X-CalculatedFETarget: namprd07-provisioning.internal.outlook.com
X-ProxyErrorLabel: ProxyHandler::OnWinHttpRequestError/WinHttpRequest::ReceiveResponse
X-ProxyErrorHResult: 0x80072efe
X-ProxyErrorMessage: The connection with the server was terminated abnormally
X-Powered-By: ASP.NET
X-FEServer: BLUPR14CA0027
X-MSEdge-Ref: Ref A: F0C2366F72364B08A9C270672FB271C1 Ref B: 1C1593F5E64AF33E0BE980EA9B1B6CDD Ref C: Thu Dec 22 00:30:31 2016 PST
Date: Thu, 22 Dec 2016 08:30:30 GMT`
Update 2
After some investigation, turns out that we are using this code:
var dataProvider = new MicrosoftProviderAdapter(new Uri("https://outlook.office.com/api/v2.0"), GetAccessToken);
var userDetail = await dataProvider.Me.ExecuteAsync();
dataProvider.Context.SendingRequest2 +=(sender,e)=>InsertXAnchorMailboxHeader(sender, e, userDetail.EmailAddress);`
to insert X-AnchorMailbox but for some reason if logged in with sheta.fadi#outlook.com the response
of await dataProvider.Me.ExecuteAsync() has outlook_F26A78076F4A0070#outlook.com as email and not sheta.fadi#outlook.com
p.s. this call worked up until last week

Related

Set Correct Encoding Type When Posting Form

I am trying to make a post using HttpClient. This is what I have tried:
public static async void DoPost(string url, string user, string password)
{
List<KeyValuePair<string, string>> postValues = new List<KeyValuePair<string, string>>();
postValues.Add(new KeyValuePair<string, string>("method", "login"));
postValues.Add(new KeyValuePair<string, string>("user", user));
postValues.Add(new KeyValuePair<string, string>("pass", password));
FormUrlEncodedContent formEnc = new FormUrlEncodedContent(postValues);
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.PostAsync(url, formEnc))
using (HttpContent content = response.Content)
{
// ... Read the string.
string result = await content.ReadAsStringAsync();
// ... Display the result.
if (result != null &&
result.Length >= 50)
{
Console.WriteLine(result.Substring(0, 50) + "...");
}
}
}
It throws an exception for not having the right encoding type. I am not sure what the encoding type should be or where to set it. This is the exception:
System.InvalidOperationException was unhandled by user code
HResult=-2146233079
Message=The character set provided in ContentType is invalid. Cannot read content as string using an invalid character set.
Source=System.Net.Http
StackTrace:
at System.Net.Http.HttpContent.ReadBufferedContentAsString()
at System.Net.Http.HttpContent.<>c.<ReadAsStringAsync>b__36_0(HttpContent s)
at System.Net.Http.HttpContent.<WaitAndReturnAsync>d__62`2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at SuiteCrmTest.Program.<DoPost>d__1.MoveNext() in D:\Projects\SuiteCrmTest\src\SuiteCrmTest\Program.cs:line 34
InnerException:
HResult=-2147024809
Message='"ISO-8859-1"' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.
Parameter name: name
ParamName=name
Source=System.Private.CoreLib
StackTrace:
at System.Globalization.EncodingTable.internalGetCodePageFromName(String name)
at System.Globalization.EncodingTable.GetCodePageFromName(String name)
at System.Text.Encoding.GetEncoding(String name)
at System.Net.Http.HttpContent.ReadBufferedContentAsString()
InnerException:
How do I set correct content type?
edit:
received headers:
HTTP/1.1 200 OK
Server: nginx/1.4.6 (Ubuntu)
Date: Sun, 07 Aug 2016 23:46:17 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
X-Powered-By: PHP/5.5.9-1ubuntu4.17
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Encoding: gzip
HTTP/1.1 500 Internal Server Error
Server: nginx/1.4.6 (Ubuntu)
Date: Sun, 07 Aug 2016 23:46:26 GMT
Content-Type: text/html; charset="ISO-8859-1"
Transfer-Encoding: chunked
Connection: keep-alive
X-Powered-By: PHP/5.5.9-1ubuntu4.17
The first header is whats causing the issues I think. The second header I think is a redirect to a html message. On the first header there is an encoded message in ISO-8859-1 which I guess is the reason it is throwing error but I don't know how to read that. How do I set the charset?
The API I was accessing allows a field to specify the return type. I specified Json in the form field and then it worked.

Using UCWA api and getting error when trying to connect through code C#

I am using UCWA api to create Lync Meeting URL but I am getting error in a step,
and it is related to LYNC so trying to figure out how to resolve. My code is
string url_00 = ucwaMsRtcOAuth;
var authDic_00 = new Dictionary<string, string>();
authDic_00.Add("grant_type", "password");
authDic_00.Add("username", String.Format("{0}\\{1}", ucwaAdDomain, ucwaAdUser));
authDic_00.Add("password", ucwaAdPassword);
httpClient.DefaultRequestHeaders.Remove("Accept");
httpClient.DefaultRequestHeaders.Add("Accept", "application/vnd.microsoft.com.ucwa+xml");
var res_00 = await httpClient.PostAsync(url_00, new FormUrlEncodedContent(authDic_00));
string res_00_request = res_00.RequestMessage.ToString();
string res_00_headers = res_00.Headers.ToString();
string res_00_status = res_00.StatusCode.ToString();
var res_00_content = await res_00.Content.ReadAsStringAsync();
and output of last 4 variable is as
res_00.RequestMessage
Method: POST, RequestUri: 'https://lynceu1webint.MYCOMPANYNAME.com/WebTicket/oauthtoken',
Version: 1.1, Content: System.Net.Http.FormUrlEncodedContent, Headers:
{
Accept: application/vnd.microsoft.com.ucwa+xml
Content-Type: application/x-www-form-urlencoded
Content-Length: 72
}
res_00.Headers
Pragma: no-cache
X-Ms-diagnostics: 28020;source="GDLYNPRFEWP01P.corp.MYCOMPANYNAME.com";reason="No valid security token."
X-MS-Server-Fqdn: GDLYNPRFEWP01P.corp.MYCOMPANYNAME.com
Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Content-Type-Options: nosniff
Cache-Control: no-store
Date: Fri, 20 May 2016 11:12:09 GMT
Server: Microsoft-IIS/8.0
X-Powered-By: ASP.NET
res_00.StatusCode
BadRequest
res_00.Content
{"error":"invalid_grant"}
There are a few potential reasons you are seeing that error response:
Incorrect domain\username combo
Incorrect password
Incorrect grant string
If you are intending to use domain and password with the password grant_type make sure your grant string resembles:
grant_type=password&domain\username&password=*******
If that still does not work you may be required to provide the SIP/Account used to login in that user to the desktop version of Skype for Business. This grant string would look like:
grant_type=password&username#domain.com&password=*******

WepAPI Method is throwing MethodNotAllowed but I don't know why

I think the answer is something simple, but I have a method throwing a 405 not allowed error and I'm not sure why. Before I get into details I'll point out something that seems like a clue - the method that works is actually called Get - and I'm not sure if there is some HTTP method mapping done behind the scenes that causes that to work.
I have a controller with multiple methods in it. So far I'm testing 2 of them and the first one works just fine, yet the second is throwing the error.
My controller is OOB setup, my logic and model are in separate projects. The following method is called and returns correctly:
[Route("api/GetFastPlan/{key}/{clientID}/{fastPlanID}")]
public RequestFastPlanResult Get(string key, string clientID, int fastPlanID)
{
return new FastPlanFileShare().RequestFastPlan(key, clientID, fastPlanID);
}
This method however is throwing a 405.
[Route("api/UpdateDownloads/{key}/{clientID}/{fastPlanID}")]
public UpdateDownloadsResult UpdateDownloads(string key
, string clientID, int fastPlanID)
{
return new FastPlanFileShare().UpdateNumberOfDownloadsColumnFastPlan(key
, clientID, fastPlanID);
}
I am calling them both with the same code setup, which is here in my test project:
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri("http://localhost:8129/api/UpdateDownloads/value1/value2/1082");
HttpResponseMessage response = httpClient.GetAsync("http://localhost:8129/api/UpdateDownloads/value1/value2/1082").Result;
Assert.IsTrue(response.IsSuccessStatusCode);
if (response.IsSuccessStatusCode)
{
var rp = response.Content.ReadAsAsync<ServiceReference2.RequestFastPlanResult>();
Assert.IsTrue(rp.Result.ServiceResult.WasSuccessful);
}
}
full error:
{StatusCode: 405, ReasonPhrase: 'Method Not Allowed', Version: 1.1,
Content: System.Net.Http.StreamContent, Headers: { Pragma: no-cache
X-SourceFiles:
=?UTF-8?B?RDpcUHJvamVjdHNcTkVUMjAxK1xFeWVNRCBFTVIgSW50ZXJuYWwgV2Vic2VydmljZXNcRU1SU2VydmljZXMuV2ViQVBJXGFwaVxVcGRhdGVEb3dubG9hZHNcZXllbWRlbXIjMVxFWUU5ODQ1NFwxMDgy?=
Cache-Control: no-cache Date: Wed, 06 Jan 2016 13:50:43 GMT
Server: Microsoft-IIS/10.0 X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET Content-Length: 72 Allow: POST
Content-Type: application/json; charset=utf-8 Expires: -1 }}

Why does C# Web Client display ? for French Characters?

My web service client is returning a ? for French characters. My client is calling an axis2/c web service on Apache. I usedwsdl.exe to generate a c# proxy class. When I look at the return in TCPMON, I can see the French characters correctly but in c# they are just showing up as ?. Here is my request and response captured from TCPMON session:
------Request ---
POST /axis2/services/Common HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 4.0.30319.18444)
VsDebuggerCausalityData: uIDPo2iKyNQi9MNOvFI9y0jK6aYAAAAA1bUF2S4JzkGiYsQ0+oayv1AuqfqiggxBj2stf8zH7O4ACQAA
Content-Type: text/xml; charset=utf-8
SOAPAction: ""
Host: localhost:9559
Content-Length: 338
Expect: 100-continue
Connection: Keep-Alive
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><getCriteria xmlns="http://Common.media.jda.com/service"><userId>2285</userId></getCriteria> </soap:Body></soap:Envelope>
----Response ------------
HTTP/1.1 100 Continue
HTTP/1.1 200 OK
Date: Wed, 10 Jun 2015 20:36:41 GMT
Server: Apache/2.2.21 (Unix) mod_ssl/2.2.21 OpenSSL/0.9.8e-fips-rhel5 Axis2C/1.6.0
Content-Length: 2052
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/xml
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> <soapenv:Body><n:getCriteriaResponse xmlns:n="http://Common.media.jda.com/service"><n:getCriteriaReturn> <n:criteriaId>18219</n:criteriaId><n:criteriaDesc>1415 S PRIMETIMEá</n:criteriaDesc><n:userId>2285</n:userId> <n:seasonCode>1415</n:seasonCode><n:marketType>S</n:marketType><n:networkCode>P</n:networkCode><n:networkDaypartId>0</n:networkDaypartId><n:salesTypeId>0</n:salesTypeId><n:advId>0</n:advId><n:agencyId>0</n:agencyId><n:acctExecId>0</n:acctExecId><n:plannerId>0</n:plannerId><n:defaultInd>false</n:defaultInd></n:getCriteriaReturn><n:getCriteriaReturn><n:criteriaId>18972</n:criteriaId><n:criteriaDesc>1415 U Daytimeá</n:criteriaDesc><n:userId>2285</n:userId><n:seasonCode>1415</n:seasonCode><n:marketType>U</n:marketType><n:networkCode>M</n:networkCode><n:networkDaypartId>0</n:networkDaypartId><n:salesTypeId>0</n:salesTypeId><n:advId>0</n:advId><n:agencyId>0</n:agencyId><n:acctExecId>0</n:acctExecId><n:plannerId>0</n:plannerId><n:defaultInd>false</n:defaultInd></n:getCriteriaReturn><n:getCriteriaReturn><n:criteriaId>18221</n:criteriaId><n:criteriaDesc>1415 U PRIMETIMEá</n:criteriaDesc><n:userId>2285</n:userId><n:seasonCode>1415</n:seasonCode><n:marketType>U</n:marketType><n:networkCode>P</n:networkCode><n:networkDaypartId>0</n:networkDaypartId><n:salesTypeId>0</n:salesTypeId><n:advId>0</n:advId><n:agencyId>0</n:agencyId><n:acctExecId>0</n:acctExecId><n:plannerId>0</n:plannerId><n:defaultInd>false</n:defaultInd></n:getCriteriaReturn><n:getCriteriaReturn><n:criteriaId>18284</n:criteriaId><n:criteriaDesc>1516 DADT Upfrontá</n:criteriaDesc><n:userId>2285</n:userId><n:seasonCode>1516</n:seasonCode><n:marketType>U</n:marketType><n:networkCode>I</n:networkCode><n:networkDaypartId>0</n:networkDaypartId><n:salesTypeId>0</n:salesTypeId><n:advId>0</n:advId><n:agencyId>0</n:agencyId><n:acctExecId>0</n:acctExecId><n:plannerId>0</n:plannerId><n:defaultInd>false</n:defaultInd></n:getCriteriaReturn></n:getCriteriaResponse> </soapenv:Body></soapenv:Envelope>
Any help would be greatly appreciated. Here is my function in the proxy class generated by wsdl.exe:
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("", RequestNamespace="http://Common.media.jda.com/service", ResponseNamespace="http://Common.media.jda.com/service", Use=System.Web.Services.Description.SoapBindingUse.Default, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
[return: System.Xml.Serialization.XmlElementAttribute("getCriteriaReturn")]
public CriteriaRec[] getCriteria(int userId) {
object[] results = this.Invoke("getCriteria", new object[] {
userId});
return ((CriteriaRec[])(results[0]));
}
I was able to resolve this issue by creating and override function:
protected override WebResponse GetWebResponse(WebRequest request)
{
WebResponse webResponse = base.GetWebResponse(request);
webResponse.Headers["Content-Type"] = "text/xml; charset=iso-8859-15";
return webResponse;
}
This works fine. In addition, I specified the requestEncoding to take care of sending data back:
myservice.RequestEncoding = System.Text.Encoding.GetEncoding("iso-8859-15");

Log In With Paypal Unauthorized 'error:access_denied'

I am attempting to set up Log In With Paypal, but I am receiving a Unauthorized Message ("{\"error_description\":\"Unable to generate token\",\"error\":\"access_denied\"}") while obtaining the access token ( I received the authorization code without a hiccup). The only thing I think I might have wrong is the availability of this service to non US residents. It says that REST APIs is not available to non US residents, but I noticed that its segregated from the 'Log In With Paypal'. Does anyone know?
Here is the code I am using too retrieve the access token in case anyone can notice an error:
string TokenEndpoint = "https://api.paypal.com/v1/identity/openidconnect/tokenservice";
System.Collections.Specialized.NameValueCollection reqparm = new System.Collections.Specialized.NameValueCollection();
reqparm.Add("client_id", this._clientId);
reqparm.Add("client_secret", this._clientSecret);
reqparm.Add("grant_type", "authorization_code");
reqparm.Add("code", authorizationCode);
reqparm.Add("redirect_uri", HttpUtility.UrlEncode(returnUrl.AbsoluteUri));
try
{
using (WebClient client = new WebClient())
{
var data = client.UploadValues(TokenEndpoint, "POST", reqparm); // Access Denied exception occurs here.
...
Here is the response I receive:
HEADER
{
Pragma: no-cache
Vary: Accept-Encoding
Connection: close
Content-Length: 72
Cache-Control: no-store
Content-Type: application/json
Date: Mon, 10 Jun 2013 23:35:02 GMT
Server: Apache-Coyote/1.1
}
Content
text
{
\"error_description\":\"Unable to generate token\",
\"error\":\"access_denied\"
}"

Categories