Video Uploading Status in Vimeo - vimeo

I am uploading video in Vimeo using my Application,But some of my videos status are not getting updated
I have followed the api document provided in this link: https://developer.vimeo.com/api/upload/videos:
I am using below code:
public boolean sendVideo(String file1, String completeURi, String endpoint, String id) throws FileNotFoundException, IOException {
File file = new File(file1);
long contentLength = file.length();
String contentLengthString = Long.toString(contentLength);
FileInputStream is = new FileInputStream(file);
int bufferSize = 20485760;
byte[] bytesPortion = new byte[bufferSize];
int byteNumber = 0;
while (is.read(bytesPortion, 0, bufferSize) != -1) {
String contentRange = Integer.toString(byteNumber);
boolean success = false;
int bytesOnServer = 0;
while (!success) {
long bytesLeft = contentLength - (bytesOnServer);
System.out.println(newline + newline + "Bytes Left: " + bytesLeft);
if (bytesLeft < bufferSize) {
//copy the bytesPortion array into a smaller array containing only the remaining bytes
bytesPortion = Arrays.copyOf(bytesPortion, (int) bytesLeft);
//This just makes it so it doesn't throw an IndexOutOfBounds exception on the next while iteration. It shouldn't get past another iteration
bufferSize = (int) bytesLeft;
}
bytesOnServer = sendVideoBytes("Vimeo Video upload", endpoint, contentLengthString, "video/mp4", contentRange, bytesPortion, first,isuploaded);
AppLog.e("bytesOnServer", "===contentLength===" + bytesOnServer +"&&=="+contentLengthString);
if (bytesOnServer >= Integer.parseInt(contentLengthString)) {
System.out.println("Success is true!");
return true;
} else {
contentRange = (bytesOnServer + 1) + "-" + (Integer.parseInt(contentLengthString)) + "/" + (Integer.parseInt(contentLengthString));
System.out.println(bytesOnServer + " != " + contentLength);
System.out.println("Success is not true!"+contentRange);
success=false;
first = true;
}
}
}
return true;
}
/**
* Sends the given bytes to the given endpoint
*
* #return the last byte on the server (from verifyUpload(endpoint))
*/
private static int sendVideoBytes(String videoTitle, String endpoint, String contentLength, String fileType, String contentRange, byte[] fileBytes, boolean addContentRange,boolean isuploaded) throws FileNotFoundException, IOException {
OAuthRequest request = new OAuthRequest(Verb.PUT, endpoint);
request.addHeader("Content-Length", contentLength);
request.addHeader("Content-Type", fileType);
if (addContentRange) {
request.addHeader("Content-Range", "bytes " + contentRange);
}
request.addPayload(fileBytes);
Response response = signAndSendToVimeo(request, "sendVideo with file bytes " + videoTitle, false);
if (response.getCode() != 200 && !response.isSuccessful()) {
return -1;
}
return verifyUpload(endpoint, contentLength, contentRange,isuploaded);
}
/**
* Verifies the upload and returns whether it's successful
*
* #param
* #param contentLength
* #param endpoint to verify upload to #return the last byte on the server
*/
public static int verifyUpload(String endpoint, String contentLength, String contentRange,boolean isuploaded) {
// Verify the upload
OAuthRequest request = new OAuthRequest(Verb.PUT, endpoint);
request.addHeader("Content-Length", "0");
request.addHeader("Content-Range", "bytes */*");
Response response = signAndSendToVimeo(request, "verifyUpload to " + endpoint, true);
AppLog.e("verifyUpload", "" + response.getCode());
if (response.getCode() != 308 || !response.isSuccessful()) {
return -1;
}
String range = response.getHeader("Range");
AppLog.e("After verify","==range header contains"+Integer.parseInt(range.substring(range.lastIndexOf("-") + 1)));
//range = "bytes=0-10485759"
return Integer.parseInt(range.substring(range.lastIndexOf("-") + 1)); //+1 remove
//return Integer.parseInt(range.substring(range.lastIndexOf("-") + 1)) + 1;
//The + 1 at the end is because Vimeo gives you 0-whatever byte where 0 = the first byte
}
public static Response signAndSendToVimeo(OAuthRequest request, String description, boolean printBody) throws org.scribe.exceptions.OAuthException {
String newline = "\n";
System.out.println(newline + newline
+ "Signing " + description + " request:"
+ ((printBody && !request.getBodyContents().isEmpty()) ? newline + "\tBody Contents:" + request.getBodyContents() : "")
+ ((!request.getHeaders().isEmpty()) ? newline + "\tHeaders: " + request.getHeaders() : ""));
service.signRequest(OAuthConstants.EMPTY_TOKEN, request);
Response response = request.send();
// AppLog.e("Uplaod Video aftre Response", "" + response.getCode());
return response;
}
Can anyone help with a working code for Android??
Thanks in advance!!

I recently had the same problem with vimeo. The api returns the state VIMUploadState_Succeeded for the upload process, but if you try to watch the video at vimeo.com it is stucked in the uploading state and it shows a black screen in the app when you try to reproduce the video.
I got the following answers from their support team:
It looks like this specific video
didn't change from the uploaded state to a failure state.
Sorry but the videos provided in those links never finished uploading
and are lost. They will need to be re-uploaded.
In our platform there are several videos uploaded everyday and it seems to have no pattern to identify when this uploading problem will happen. If it is not a problem for you to re-upload the video, vimeo can be a good solution since its price is really good in comparison to other video platforms, otherwise you should look for another video storage/playback solution.

It is difficult to check up your code without proper debugging.
Here's the workaround for your code with a little more functions added
You can check the code here

Related

Printing ArrayList values in SpringBoot

I created an ArrayList with the json values from an Rest API.
This is the code to read the Rest API:
#RestController
public class exemploclass {
#RequestMapping(value="/vectors")
//#Scheduled(fixedRate = 5000)
public ArrayList<StateVector> getStateVectors() throws Exception {
ArrayList<StateVector> vectors = new ArrayList<>();
String url = "https://opensky-network.org/api/states/all?lamin=41.1&lomin=6.1&lamax=43.1&lomax=8.1";
//String url = "https://opensky-network.org/api/states/all?lamin=45.8389&lomin=5.9962&lamax=47.8229&lomax=10.5226";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", "Mozilla/5.0");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JSONObject myResponse = new JSONObject(response.toString());
JSONArray states = myResponse.getJSONArray("states");
System.out.println("result after Reading JSON Response");
for (int i = 0; i < states.length(); i++) {
JSONArray jsonVector = states.getJSONArray(i);
String icao24 = jsonVector.optString(0);
String callsign = jsonVector.optString(1);
String origin_country = jsonVector.optString(2);
Boolean on_ground = jsonVector.optBoolean(8);
//System.out.println("icao24: " + icao24 + "| callsign: " + callsign + "| origin_country: " + origin_country + "| on_ground: " + on_ground);
//System.out.println("\n");
StateVector sv = new StateVector(icao24, callsign, origin_country, on_ground);
vectors.add(sv);
}
System.out.println("Size of data: " + vectors.size());
return vectors;
}
}
The last line " return vectors;" returns a list with the values i parsed and returns it like this:
But i want this more "pretty", i want it to be one Array in each line, how can i achieve this?
P.S. Its on the .html page, not on console
Your return value seems a valid Json Object. If you want it more pretty so you can read it clearly then pass it through an application that makes that json pretty.
If you call your API from Postman, it will give you a pretty Json Object which will be better formatted. This will be because you have annotated your controller with #RestController so it will deliver an application/json response which Postman will know and then it will try to make it prettier.
P.S. Its on the .html page, not on console
So you hit your API from a browser. Most browsers don't expect a Json object to be returned, so they will not make it pretty. You can't force that from your Service either.
Just hit your API from Postman, it will understand it and make it pretty.

Why the custom exception message from an exception is not shown in a Xamarin solution?

I have been understanding this example for Xamarin cross-platform mobile development:
https://msdn.microsoft.com/en-us/library/dn879698.aspx
I made an error by copying two times the the API key in the code:
using System;
using System.Threading.Tasks;
namespace XWeatherApp
{
public class Core
{
public static async Task<Weather> GetWeather(string zipCode)
{
//Sign up for a free API key at http://openweathermap.org/appid
string key = "40aabb59f41e9e88db7be4bab11f49f8";
string queryString = "http://api.openweathermap.org/data/2.5/weather?zip="
+ zipCode + ",us&appid=" + key + "&units=imperial";
//Make sure developers running this sample replaced the API key
if (key == "40aabb59f41e9e88db7be4bab11f49f8")
{
throw new ArgumentException("You must obtain an API key from openweathermap.org/appid and save it in the 'key' variable.");
}
dynamic results = await DataService.getDataFromService(queryString).ConfigureAwait(true);
if (results["weather"] != null)
{
Weather weather = new Weather();
weather.Title = (string)results["name"];
weather.Temperature = (string)results["main"]["temp"] + " F";
weather.Wind = (string)results["wind"]["speed"] + " mph";
weather.Humidity = (string)results["main"]["humidity"] + " %";
weather.Visibility = (string)results["weather"][0]["main"];
DateTime time = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
DateTime sunrise = time.AddSeconds((double)results["sys"]["sunrise"]);
DateTime sunset = time.AddSeconds((double)results["sys"]["sunset"]);
weather.Sunrise = sunrise.ToString() + " UTC";
weather.Sunset = sunset.ToString() + " UTC";
return weather;
}
else
{
return null;
}
}
}
}
Specifically, in the lines after the two comments.
I deployed the app to a physical Android phone. Obviously I got an exception (this was not so obvious after some minutes looking for the failing code).
That exception wasn't displayed in the Output window (in Visual Studio 2017). I just only got this message on screen:
Why don't the custom message for the exception (i.e., You must obtain an API key from openweathermap.org/appid and save it in the 'key' variable.).
Have you tried to use a try/catch?
something like
try{
await GetWeather(string zipCode);
}
catch(Exception ex) {
// here you should have your exception
}

Transfer ownership of file uploaded using Google drive API

The Google Drive API is not able to transfer ownership of a file which was uploaded from the API itself.
as per the API documentation, PUT needs to be used for transferring ownership.
when I use it with the parameters required it returns existing permission back.
doesn't update it with new owner.
if i use POST & the required parameters it throws 'The remote server returned an error: (400) Bad Request.'
I was able to change the ownership for the files that were NOT uploaded via API. the same which I use for the files which are uploaded from API. the owner doesn't change.
Is it a bug or I am doing something wrong?
-EDIT-
if anyone wants details of file uploaded using API & file created via gdocs I can.
-EDIT2-
public bool UploadReportToGoogleDrive(Model model, byte[] ReportPDF_ByteArray, string ddlAddFilesFolder = "root", bool doNotify = true)
{
bool isErrorOccured = false;
try
{
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - start");
FileList fileList = new FileList();
Google.Apis.Drive.v2.Data.File uploadedFile = new Google.Apis.Drive.v2.Data.File();
Permission writerPermission = new Permission();
string accessToken = GetAccessToken();
#region FIND REPORT FOLDER
string url = "https://www.googleapis.com/drive/v2/files?"
+ "access_token=" + accessToken
+ "&q=" + HttpUtility.UrlEncode("title='My Reports' and trashed=false and mimeType in 'application/vnd.google-apps.folder'")
;
// Create POST data and convert it to a byte array.
List<string> _postData = new List<string>();
string postData = string.Join("", _postData.ToArray());
try
{
WebRequest request = WebRequest.Create(url);
string responseString = GDriveHelper.GetResponse(request);
fileList = JsonConvert.DeserializeObject<FileList>(responseString);
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - folder search success");
}
catch (Exception ex)
{
SingletonLogger.Instance.Error("UploadReportToGoogleDrive\\FIND REPORT FOLDER", ex);
isErrorOccured = true;
}
#endregion FIND REPORT FOLDER
if (fileList.Items.Count == 0)
{
#region CREATE REPORT FOLDER
url = "https://www.googleapis.com/drive/v2/files?" + "access_token=" + accessToken;
// Create POST data and convert it to a byte array.
_postData = new List<string>();
_postData.Add("{");
_postData.Add("\"title\": \"" + "My Reports" + "\",");
_postData.Add("\"description\": \"Uploaded with Google Drive API\",");
_postData.Add("\"parents\": [{\"id\":\"" + "root" + "\"}],");
_postData.Add("\"mimeType\": \"" + "application/vnd.google-apps.folder" + "\"");
_postData.Add("}");
postData = string.Join("", _postData.ToArray());
try
{
WebRequest request = WebRequest.Create(url);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
// Set the ContentLength property of the WebRequest.
request.ContentLength = postData.Length;//byteArray.Length;
// Set the Method property of the request to POST.
request.Method = "POST";
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
string responseString = GDriveHelper.GetResponse(request);
Google.Apis.Drive.v2.Data.File ReportFolder = JsonConvert.DeserializeObject<Google.Apis.Drive.v2.Data.File>(responseString);
;
ddlAddFilesFolder = ReportFolder.Id;
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - folder creation success");
}
catch (Exception ex)
{
SingletonLogger.Instance.Error("UploadReportToGoogleDrive\\CREATE REPORT FOLDER", ex);
isErrorOccured = true;
}
#endregion CREATE REPORT FOLDER
}
else
{
ddlAddFilesFolder = fileList.Items.FirstOrDefault().Id;
}
if (!isErrorOccured)
{
#region UPLOAD NEW FILE - STACKOVER FLOW
//Createing the MetaData to send
_postData = new List<string>();
_postData.Add("{");
_postData.Add("\"title\": \"" + "Report_" + model.id + "\",");
_postData.Add("\"description\": \"" + " report of person - " + (model.borrowerDetails.firstName + " " + model.borrowerDetails.lastName) + "\",");
_postData.Add("\"parents\": [{\"id\":\"" + ddlAddFilesFolder + "\"}],");
_postData.Add("\"extension\": \"" + "pdf" + "\",");
_postData.Add("\"appDataContents\": \"" + true + "\",");
_postData.Add("\"mimeType\": \"" + GDriveHelper.GetMimeType("Report.pdf").ToString() + "\"");
_postData.Add("}");
postData = string.Join(" ", _postData.ToArray());
byte[] MetaDataByteArray = Encoding.UTF8.GetBytes(postData);
//// creating the Data For the file
//MemoryStream target = new MemoryStream();
//myFile.InputStream.Position = 0;
//myFile.InputStream.CopyTo(target);
//byte[] FileByteArray = target.ToArray();
string boundry = "foo_bar_baz";
url = "https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart" + "&access_token=" + accessToken;
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "multipart/related; boundary=\"" + boundry + "\"";
// Wrighting Meta Data
string headerJson = string.Format("--{0}\r\nContent-Type: {1}\r\n\r\n",
boundry,
"application/json; charset=UTF-8");
string headerFile = string.Format("\r\n--{0}\r\nContent-Type: {1}\r\n\r\n",
boundry,
GDriveHelper.GetMimeType("Report.pdf").ToString());
string footer = "\r\n--" + boundry + "--\r\n";
int headerLenght = headerJson.Length + headerFile.Length + footer.Length;
request.ContentLength = MetaDataByteArray.Length + ReportPDF_ByteArray.Length + headerLenght;
Stream dataStream = request.GetRequestStream();
dataStream.Write(Encoding.UTF8.GetBytes(headerJson), 0, Encoding.UTF8.GetByteCount(headerJson)); // write the MetaData ContentType
dataStream.Write(MetaDataByteArray, 0, MetaDataByteArray.Length); // write the MetaData
dataStream.Write(Encoding.UTF8.GetBytes(headerFile), 0, Encoding.UTF8.GetByteCount(headerFile)); // write the File ContentType
dataStream.Write(ReportPDF_ByteArray, 0, ReportPDF_ByteArray.Length); // write the file
// Add the end of the request. Start with a newline
dataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer));
dataStream.Close();
try
{
WebResponse response = request.GetResponse();
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
//Console.WriteLine(responseFromServer);
uploadedFile = JsonConvert.DeserializeObject<Google.Apis.Drive.v2.Data.File>(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - upload to folder success");
}
catch (Exception ex)
{
SingletonLogger.Instance.Error("UploadReportToGoogleDrive\\CREATE REPORT FOLDER", ex);
isErrorOccured = true;
//return "Exception uploading file: uploading file." + ex.Message;
}
#endregion UPLOAD NEW FILE - STACKOVER FLOW
}
if (!isErrorOccured)
{
#region MAKE ADMIN ACCOUNT OWNER OF UPLOADED FILE - COMMENTED
url = "https://www.googleapis.com/drive/v2/files/" + uploadedFile.Id
+ "/permissions/"
+ uploadedFile.Owners[0].PermissionId
+ "?access_token=" + accessToken
+ "&sendNotificationEmails=" + (doNotify ? "true" : "false")
;
WebRequest request = WebRequest.Create(url);
string role = "owner", type = "user", value = "aniketpatil87#gmail.com";
// Create POST data and convert it to a byte array.
postData = "{"
+ "\"role\":\"" + role + "\""
+ ",\"type\": \"" + type + "\""
+ ",\"value\": \"" + value + "\""
+ ",\"permissionId\":\"" + uploadedFile.Owners[0].PermissionId + "\""
+ ",\"transferOwnership\": \"" + "true" + "\""
+ "}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
// Set the ContentLength property of the WebRequest.
request.ContentLength = postData.Length;//byteArray.Length;
// Set the Method property of the request to POST.
request.Method = "POST";
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
//TRY CATCH - IF TOKEN IS INVALID
try
{
string responseString = GDriveHelper.GetResponse(request);
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - make admin account owner success");
}
catch (Exception ex)
{
SingletonLogger.Instance.Error("UploadReportToGoogleDrive\\MAKE ADMIN ACCOUNT OWNER OF UPLOADED FILE", ex);
isErrorOccured = true;
}
#endregion MAKE ADMIN ACCOUNT OWNER OF UPLOADED FILE
if (model.Officer != default(int))
{
#region ALLOW OFFICER TO ACCESS UPLOADED FILE
OldModels.MWUsers officer = usersBL.GetAll(model.Officer).FirstOrDefault();
url = "https://www.googleapis.com/drive/v2/files/" + uploadedFile.Id
+ "/permissions/"
//+ uploadedFile.Owners[0].PermissionId
+ "?access_token=" + accessToken
+ "&sendNotificationEmails=" + (doNotify ? "true" : "false")
;
request = WebRequest.Create(url);
role = "writer";
type = "user";
value = Officer.EMail;
// Create POST data and convert it to a byte array.
postData = "{"
+ "\"role\":\"" + role + "\""
+ ",\"type\": \"" + type + "\""
+ ",\"value\": \"" + value + "\""
//+ ",\"permissionId\":\"" + uploadedFile.Owners[0].PermissionId + "\""
//+ ",\"transferOwnership\": \"" + "true" + "\""
+ "}";
byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
// Set the ContentLength property of the WebRequest.
request.ContentLength = postData.Length;//byteArray.Length;
// Set the Method property of the request to POST.
request.Method = "POST";
// Get the request stream.
dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
//TRY CATCH - IF TOKEN IS INVALID
try
{
string responseString = GDriveHelper.GetResponse(request);
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - make officer writer success");
}
catch (Exception ex)
{
SingletonLogger.Instance.Error("UploadReportToGoogleDrive\\ALLOW OFFICER TO ACCESS UPLOADED FILE", ex);
isErrorOccured = true;
}
#endregion ALLOW OFFICER TO ACCESS UPLOADED FILE
}
}
if (isErrorOccured)
{
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - report upload to gdrive failed");
}
else
{
//LogHelper.CreateLogEntry(UserContext.CurrentUser.UserID, "Uploaded " + myFileList.Count + " file(s) on Google Drive.", this.HttpContext.Request);
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - report upload to gdrive success");
}
}
catch (Exception ex)
{
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - Outer exception", ex);
isErrorOccured = true;
}
return isErrorOccured;
}
Not sure if you've looked at the PATCH command for permissions. The PATCH command with the proper parameters lets you transfer ownership.
Link to Google Drive API documentation
It looks like you are specifying transferOwnership in the post body, when it must be specified as a URL parameter, as per the documentation.

WP8 - Scheduled Task Agent for push notifications

I'm trying to interface my app with push notifications and the backend developer choose Pusher as notifications provider.
.NET SDK is very messy, untidy and synchronous, which it does not work on WP8, so I rewrote its and it works fine now.
The question is: is a Scheduled Task required for fetch the push notifications and update the tile/toast? Or there are any best method?
I can't change push provider sadly.
You can simply send Tile and Toast push notifications to the phone and they will work even if your app is not running. You do not need background task for that.
Here is sample code that I use in a desktop application to send push notifications to a Windows Phone 8.0:
const String toastTemplate =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<wp:Notification xmlns:wp=\"WPNotification\">" +
"<wp:Toast>" +
"<wp:Text1>{0}</wp:Text1>" +
"<wp:Text2>{1}</wp:Text2>" +
"<wp:Param>{2}</wp:Param>" +
"</wp:Toast>" +
"</wp:Notification>";
String message = String.Format(toastTemplate, "Test", "updated: " + DateTime.Now.ToString(), "/Pages/SyncPage.xaml");
Status = await PushNotifiactionsManager.SendNotification(cfg.PushNotificationUri, message, 2);
public static async Task<string> SendNotification(string pushNotificationUri, string message, short notificationClass)
{
String responseText;
if (message.Length > 3072)
{
responseText = String.Format("The message must be <= 3072 bytes: {0}", message);
}
else
{
HttpClient request = new HttpClient();
// Add message headers.
request.DefaultRequestHeaders.Add("X-MessageID", Guid.NewGuid().ToString());
request.DefaultRequestHeaders.Add("X-NotificationClass", notificationClass.ToString());
if (notificationClass == 1)
{
request.DefaultRequestHeaders.Add("X-WindowsPhone-Target", "token");
}
else if (notificationClass == 2)
{
request.DefaultRequestHeaders.Add("X-WindowsPhone-Target", "toast");
}
try
{
// Send the message, and wait for the response.
HttpResponseMessage response = await request.PostAsync(pushNotificationUri, new StringContent(message));
IEnumerable<string> values;
String connectionStatus = String.Empty;
if (response.Headers.TryGetValues("X-DeviceConnectionStatus", out values))
{
connectionStatus = values.First();
}
String subscriptionStatus = String.Empty;
if (response.Headers.TryGetValues("X-SubscriptionStatus", out values))
{
subscriptionStatus = values.First();
}
String notificationStatus = String.Empty;
if (response.Headers.TryGetValues("X-NotificationStatus", out values))
{
notificationStatus = values.First();
}
responseText = String.Format("{0}: {1}, {2}, {3}, {4}",
notificationClass == 1 ? "Tile" :
notificationClass == 2 ? "Toast" : "Raw",
response.StatusCode,
connectionStatus, subscriptionStatus, notificationStatus);
}
catch (WebException ex)
{
responseText = ex.Message;
}
}
return "Notification response: " + responseText;
}

Fetch raw e-mail text with EWS (headers, body and encoded attachments)

Is there a way to fetch the raw email text using EWS?
I would like to get the whole text including headers, body, and encoded attachments.
Is this possible?
I don't know if this is what you are looking for, but it should help.
It downloads the entire message file, including encoded attachments, header, subject, sender, receiver, etc...
try this:
static void Main(string[] args)
{
try
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
service.Credentials = new NetworkCredential("USR", "PWD", "Domain");
service.AutodiscoverUrl("someone#example.com");
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(int.MaxValue));
Console.WriteLine("Found : " + findResults.TotalCount + " messages");
foreach (EmailMessage message in findResults.Items)
{
try
{
message.Load(new PropertySet(ItemSchema.MimeContent));
MimeContent mc = message.MimeContent;
// I use this format to rename messages files, you can do whatever you want
string n = string.Format("-{0:yyyy-MM-dd_HH-mm-ss-ffff}.eml", DateTime.Now);
string path = #"C:\folder\message" + n;
FileStream fs = new FileStream(path, FileMode.Create);
fs.Write(mc.Content, 0, mc.Content.Length);
fs.Flush();
fs.Close();
//message.Delete(DeleteMode.HardDelete); // It deletes the messages permanently
//message.Delete(DeleteMode.MoveToDeletedItems); // It moves the processed messages to "Deleted Items" folder
}
catch (Exception exp)
{
Console.WriteLine("Error : " + exp);
}
}
}
catch (Exception exp2)
{
Console.WriteLine("Error : " + exp2);
}
}
Hope it helps, cheers.