mailboxUsageDetailsRequest returns exception - microsoft-graph-sdks

Replacing MSOnline cmdlets with Microsoft.Graph V1.12.0.
Report mailboxUsageDetailsReport = null;
IReportRootGetMailboxUsageDetailRequestBuilder mailboxUsageDetailsRequestBuilder = null;
IReportRootGetMailboxUsageDetailRequest mailboxUsageDetailsRequest = null;
mailboxUsageDetailsRequestBuilder = graphServiceClient.Reports.GetMailboxUsageDetail(period);
mailboxUsageDetailsRequest = mailboxUsageDetailsRequestBuilder.Request();
mailboxUsageDetailsReport = await mailboxUsageDetailsRequest.GetAsync();
The last line throws:
Newtonsoft.Json.JsonReaderException
HResult=0x80131500
Message=Unexpected character encountered while parsing value: R. Path '', line 0, position 0.
Source=Newtonsoft.Json
Fiddler shows 302 response with correct file "Location" but body of response contains just a 0,
Work around is
HttpRequestMessage hrm = new HttpRequestMessage(HttpMethod.Get, mailboxUsageDetailsRequest.RequestUrl);
await graphClient.AuthenticationProvider.AuthenticateRequestAsync(hrm);
HttpResponseMessage response = await graphClient.HttpProvider.SendAsync(hrm);

The Microsoft Graph .Net client v1.12.0 does not currently support the Reports API in a first class manner. You are sharing the suggested workaround, we thank you for sharing that. The response is a csv file, that's why you see the JsonReaderException.

Related

FormatException (FormatException: Unexpected character (at character 1)

I am trying to get data from a json from a link and decode it to display data in a calendar, so it worked fine until this error appears in this line
dynamic jsonAppData = convert.jsonDecode(data.body);
Which trows this:
Exception has occurred. FormatException (FormatException: Unexpected
character (at character 1) <!doctype html><base href="https://accou... ^ )
I don't really know why it is caused, I searched for solutions but I didn't find anything for my case.
I hope you can help me.
Future<List> getDataFromGoogleSheet() async {
Response data = await http.get(
Uri.parse(
"https://script.google.com/macros/s/AKfycbybaFrTEBrxTIni8izFKMQYNNAe7ciVMlqF0OUHyWujjRR2AQ8zDyQzh96tleRKMHSN/exec"),
);
dynamic jsonAppData = convert.jsonDecode(data.body);
final List<Meeting> appointmentData = [];
for (dynamic data in jsonAppData) {
var recurrence = data['byday'];
Meeting meetingData = Meeting(
eventName: data['subject'],
from: _convertDateFromString(data['starttime']),
to: _convertDateFromString(data['endtime']),
background: Colors.grey.shade800,
recurrenceRule: 'FREQ=DAILY;INTERVAL=7;BYDAY:$recurrence;COUNT=10',
);
appointmentData.add(meetingData);
String notes = data['notes'];
}
return appointmentData; }
Your response body is not of json type.
You should check your request before
You can't parse the json because you have to authenticate with google first. If you call the page in the browser, where you are not logged in with Google, then you are redirected to the login page of Google. And my guess is this page is parsed, not the json.

JSON - WepAPI - Unexpected character encountered while parsing value

ANY help will be greatly appreciated
I have a Generic class that facilitates WebAPI calls, Its been in place for quite sometime and has had no issue. Today I'm getting an error and not sure where to track the problem. the exact error is
{"Unexpected character encountered while parsing value: [. Path 'PayLoad', line 1, position 12."}
what I'm getting back as the result of the call is
"{\"PayLoad\":[\"file_upload_null20180629155922²AAGUWVP2XUezeM3CiEnSOw.pdf\"],\"Success\":true,\"Message\":\"1 File(s) Uploaded\",\"Exceptions\":[]}"
Which looks right and is what I expect back from the service call
Here is the method that I'm calling that suddenly quit working, and its failing on the last line
public static TR WebApiPost(string serveraddress, string endpoint, object data)
{
HttpResponseMessage msg;
var clienthandler = new HttpClientHandler
{
UseDefaultCredentials = false,
Credentials = new NetworkCredential(user, password, domain)
};
using (var client = new HttpClient(clienthandler) { BaseAddress = new Uri(serveraddress) })
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
msg = client.PostAsync(endpoint, new StringContent(new JavaScriptSerializer().Serialize(data), Encoding.UTF8, "application/json")).Result;
}
var result = msg.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<TR>(result);
}
AND finally the line that actually makes the call (which should not matter)
returned = CallHelper<ResultStatus<string>>.WebApiPost(serviceurl, sendFileUrl, model);
It's not clear where your web service is getting the value of PayLoad from, so it is very possible that the value has a Byte Order Mark (BOM) at its beginning. This is especially the case if you are returning the content of what was originally a Unicode encoded file.
Be aware that a BOM is NOT visible when you are viewing a string in the debugger.
On your web service, make sure that you are not returning a BOM in the value of PayLoad. Check for this byte sequence at the beginning of the string:
0xEF,0xBB,0xBF
For more information on Byte Order Mark:
https://en.wikipedia.org/wiki/Byte_order_mark

Bad Request -Post method - JSON DateTime issue

I have a Visual Studio (2015) project that includes a client part (Xamarin.Forms PCL) and a web service part ( WCF Rest). The web services use edmx to communicate with the database ( SQL Server 2016). JSON is used to exchange the data.
I'm new to creating/consuming WCF Rest services. I have no issue using the GET method but I'm stuck with an issue with a POST method.
This method is part of a service that works well: no issue for a GET based method. It works well when I test it from a URL or from my client ( PCL Xamarin.Forms).
The POST method (my first ever) is a bit more problematic.
It's supposed to create a new record in a table in SQL Server (2016).
When I use Postman (https://www.getpostman.com/) to test it, it already has an issue: it creates a record in the table but the object has two dates and the two dates are replaced by 1970-01-01.
When I use my client to contact the web service:I get 'Bad Request'.
I looked for a solution and found that instead of placing the Datetime value, it was best to place the number of milliseconds from 1970-01-01.
I used this advice in Postman and noticed the creation of a new line worked fine.
Body of the Postman request :
{
"Reservation_Utilisateur_Id" : "4",
"Reservation_Velo_Id" : "2",
"Reservation_DateDebut" : "\/Date(1245398693390)\/",
"Reservation_PeriodeDebut" : "matin",
"Reservation_DateFin" :"\/Date(1245398693390)\/",
"Reservation_PeriodeFin" : "matin"
}
Now, I'd like to know how to get that object to send to the server . How can my object be serialized like above?
I looked for a solution unsuccessfully.
I keep on getting "There was an error deserializing the object of type BikeSharingService.Reservation. DateTime content '2016-08-22T00:00:00+02:00' does not start with '/Date(' and end with ')/' as required for JSON."
Could someone please give the newbie that I am an explanation and maybe some code that works?
Here is my code:
My contract:
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "create",
ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
Reservation create(Reservation reservation);
The service method:
public Reservation create(Reservation reservation)
{
using (MyEntities bse = new MyEntities())
{
Reservation re = new Reservation
{
Reservation_Utilisateur_Id = reservation.Reservation_Utilisateur_Id,
Reservation_Velo_Id = reservation.Reservation_Velo_Id,
Reservation_DateDebut = reservation.Reservation_DateDebut,
Reservation_PeriodeDebut = reservation.Reservation_PeriodeDebut,
Reservation_DateFin = reservation.Reservation_DateFin,
Reservation_PeriodeFin = reservation.Reservation_PeriodeFin,
Reservation_DemandeRecupDomCli = reservation.Reservation_DemandeRecupDomCli
};
bse.Reservations.Add(re);
bse.SaveChanges();
return re;
}
}
On the client side :
const string Url1 = "http://localhost:51843/ServiceReservation.svc/create";
public async Task<Reservation> create(Reservation reservation)
{
string json = JsonConvert.SerializeObject(reservation);
var client = new HttpClient();
client.DefaultRequestHeaders.Add("Accept", "application/json");
var response = await client.PostAsync(Url1,
new StringContent(
json,
Encoding.UTF8, "application/json"));
return JsonConvert.DeserializeObject<Reservation>(
await response.Content.ReadAsStringAsync());
}
Then calling the method on the client side :
Reservation re =new Reservation();
re.Reservation_Utilisateur_Id = 4;
re.Reservation_Velo_Id = 2;
re.Reservation_DateDebut = DateTime.Now.Date;
re.Reservation_PeriodeDebut = "matin";
re.Reservation_DateFin = DateTime.Now.Date;
re.Reservation_PeriodeFin = "matin";
re.Reservation_DemandeRecupDomCli = 1;
Reservation resultat = await reManager.create(re);
What I get :
False Bad Request Method: POST, RequestUri:
'http://localhost:51843/ServiceReservation.svc /create', Version: 2.0,
Content: System.Net.Http.StringContent, Headers: { Accept:
application/json Content-Type: application/json; charset=utf-8
Content-Length: 407 } BadRequest
1.1
There was an error deserializing the object of type
BikeSharingService.Reservation. DateTime content
'2016-08-22T00:00:00+02:00' does not start with '/Date(' and end with
')/' as required for JSON.
[Promoted from a comment]
Json doesn't define a standard date format, but it's worth noting that Json.Net (which is used by most of the web-facing parts of the .Net framework) supports multiple formats out of the box (and even custom ones).
If you can decide on a standard which works for all your clients, you can configure the Json (en/de)coding in .Net to use it natively.
See http://newtonsoft.com/json/help/html/datesinjson.htm for more information and details on how to specify a date format handler.
[Example code from link]
public void WriteJsonDates()
{
LogEntry entry = new LogEntry
{
LogDate = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc),
Details = "Application started."
};
// default as of Json.NET 4.5
string isoJson = JsonConvert.SerializeObject(entry);
// {"Details":"Application started.","LogDate":"2009-02-15T00:00:00Z"}
JsonSerializerSettings microsoftDateFormatSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
};
string microsoftJson = JsonConvert.SerializeObject(entry, microsoftDateFormatSettings);
// {"Details":"Application started.","LogDate":"\/Date(1234656000000)\/"}
string javascriptJson = JsonConvert.SerializeObject(entry, new JavaScriptDateTimeConverter());
// {"Details":"Application started.","LogDate":new Date(1234656000000)}
}
What you are trying to use is the Epoch DateTime or Unix DateTime.
To convert the DateTime object to epoch datetime you can create a helper method. It is either milliseconds or seconds from 1/1/1970.
Also if needed you can use the Noda DateTime instead of the .NET which has the method in it to convert.
You can create a New class with string data type for DateTime and have a Casting specified. Or you can write your on custom Serialize method.
By default DateTime format after serialization would be ISO 8601 Format.
Code to convert to Unix or Epoch Date time :
private static readonly DateTime EpochDateTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public static long ConvertDateTimeToUnixTime(DateTime date, bool isDatarequiredInMilliSeconds = false, DateTimeKind dateTimeKind = DateTimeKind.Local)
{
return Convert.ToInt64((DateTime.SpecifyKind(date.Value, dateTimeKind).ToUniversalTime() - EpochDateTime).TotalSeconds) * (isDatarequiredInMilliSeconds ? 1000 : 1);
}
You can use the following if you need to convert back(source):
var milliseconds = "/Date(1245398693390)/".replace(/\/Date\((-?\d+)\)\//, '$1');
var actualDate = new Date(parseInt(milliseconds));

WCF GET returning XML instead of JSON on server

I have a WCF service with a webHttpBinding defined. The interface has a single method:
[OperationContract(Action = "*")]
[WebGet(UriTemplate = "/",RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
Stream GetServerInfo();
Which returns a stream with encoded JSON:
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
ServerData r = ServerData.Instance;
r.upTime = (DateTime.Now - r._startupTime).ToString(#"dd\.hh\:mm\:ss");
using (Process proc = Process.GetCurrentProcess())
{
r.usedMemory = ((double)proc.PrivateMemorySize64) / 1024 / 1024;
}
r.activeSessions = getServiceData().Count();
string jsCode = "displayData" + "("+
new JavaScriptSerializer().Serialize(r)
+")";
WebOperationContext.Current.OutgoingResponse.ContentType = "application/javascript";
Console.WriteLine(jsCode);
return new MemoryStream(Encoding.UTF8.GetBytes(jsCode));
When used on my devel PC it works fine. I get sth like:
displayData({"_startupTime":"\/Date(1435867525056)\/","serverVersion":"1.0.0.8","startUpTime":"2. 7. 2015 22:05:25","acceptedConnections":0,"upTime":"00.00:00:00","usedMemory":21.265625,"activeSessions":0})
However, after deploy to a remote server I get only following response and I want to get a JSON:
<GetServerInfoResponse xmlns="http://tempuri.org/"><GetServerInfoResult>ZGlzcGxheURhdGEoeyJfc3RhcnR1cFRpbWUiOiJcL0RhdGUoMTQzNTg2ODUwMjc5NClcLyIsInNlcnZlclZlcnNpb24iOiIxLjAuMC44Iiwic3RhcnRVcFRpbWUiOiI3LzIvMjAxNSAxOjIxOjQyIFBNIiwiYWNjZXB0ZWRDb25uZWN0aW9ucyI6MCwidXBUaW1lIjoiMDAuMDA6MDA6MDAiLCJ1c2VkTWVtb3J5IjoyNy40NzY1NjI1LCJhY3RpdmVTZXNzaW9ucyI6MH0p</GetServerInfoResult></GetServerInfoResponse>
Note I call for the request locally directly on the server. But on remote call over network the response is the same. If I put a log output of the string to console I can see the output string is correct.
The config files are identical (except for addresses).
--edit
With the try-fail method I found out the string inside the XML response is the JSON string encoded in Base64.
Can somebody please help me whats wrong?
After some research I did not find any solution. However, after restarting OS (Win Server 2012) and rebuilding it just works like a charm.

C# Box-API [net_WebHeaderInvalidControlChars] received when downloading a file with Korean filename or when the file is corrupted

I received the following error when downloading from Box server:
InnerException {System.ArgumentException: [net_WebHeaderInvalidControlChars]
Arguments:
Debugging resource strings are unavailable. Often the key and arguments provide sufficient information to diagnose the problem. See http://go.microsoft.com/fwlink/?linkid=106663&Version=4.7.60408.0&File=System.Net.dll&Key=net_WebHeaderInvalidControlChars
Parameter name: name
at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClasse.<EndGetResponse>b__d(Object sendState)
at System.Net.Browser.AsyncHelper.<>c__DisplayClass1.<BeginOnUI>b__0(Object sendState)} System.Exception {System.ArgumentException}
Shown below is the code snippet.
using (HttpClient client = new HttpClient(handler) { MaxResponseContentBufferSize = Int32.MaxValue })
{
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
try
{
var fileResponse = await client.GetAsync(requestUrl, HttpCompletionOption.ResponseHeadersRead);
if (fileResponse != null && fileResponse.StatusCode == System.Net.HttpStatusCode.OK)
return await fileResponse.Content.ReadAsByteArrayAsync();
else return null;
}
catch(Exception e)
{
System.Diagnostics.Debug.WriteLine("Error in getAsync, " + e.StackTrace);
return null;
}
}
Note that this only happens for files with Korean (non-English) filenames and corrupted files. For image files and non-corrupted files, I was able to download successfully. (Example of corrupted file is a word or ppt file that shows an error msg when opened).
Having the same issue in windows phone 8.
I tried
HttpResponseMessage response = await httpClient.SendAsync(requestMessage);
I tried
WebClient client = new WebClient();
client.OpenReadAsync(new Uri(url,UriKind.RelativeOrAbsolute));
I tried IRestResponse from RestClient
All resulting in exception with empty value and inner exception net_WebHeaderInvalidControlChars.
The problem was that the user agent passed from windows client was not recognized server side. As a result, one from the returned response headers, was making .Net to crash in a lower level and the response could not be processed.
Adding NativeHost as the recognized UserAgent fixed the exception