I'm trying to read the messages from the Google API but when I check the Payload.Body.Data to see the content of the email always comes null.
But when I use Raw format I see the body but it's a little complicated to handle the information because it's in a huge and dirty string.
public static Message GetMessage(GmailService service, String userId, String messageId)
{
try
{
var request = service.Users.Messages.Get(userId, messageId);
request.Format = Google.Apis.Gmail.v1.UsersResource.MessagesResource.GetRequest.FormatEnum.Full;
var message = request.Execute();
return message;
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
}
return null;
}
Related
I've updated my plist to LSApplicationQueriesSchemes value: mailto and I still receieve the error:
-canOpenURL: failed for URL: "mailto:" - error: "This app is not allowed to query for scheme mailto"
Any advice on this? I'd like an email I've constructed to be sent to the user on click.
code
public async Task SendEmail(string body, List recipient)
{
try
{
var message = new EmailMessage
{
Subject = "Password Reset",
Body = body,
To = recipient,
//Cc = ccRecipients,
//Bcc = bccRecipients
};
await Email.ComposeAsync(message);
}
catch (FeatureNotSupportedException fbsEx)
{
// Email is not supported on this device
}
catch (Exception ex)
{
// Some other exception occurred
}
}
code
I have a requirement where I have been posting data to a web API as a json string in a POST request and the post method retrieves the data from the body. This works perfectly for most data, but it does not work when I include a long dash(—) as part of the data in any fields.
I have a Email class with some string fields and I am passing it to the API to save in the database.
Here is how I am implementing the call:
public string PostNewEmailRecord(string APIEndpoint, CampaignWave Email)
{
string StrEmailId = string.Empty;
_endpoint = APIEndpoint;
try
{
string strData = JsonConvert.SerializeObject(Email);
_client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
_client.UploadString(APIEndpoint, _requestType, strData);
}
catch (Exception ex)
{
}
return StrEmailId;
}
And here is the post method of Web API:
public void Post([FromBody]CampaignWave email)
{
try
{
using (var transaction = new TransactionScope())
{
CampaignWaveRepository cr = new CampaignWaveRepository();
object objReturnValue = cr.Insert(email);
transaction.Complete();
}
}
catch (Exception ex)
{
}
finally
{
}
}
When I include a dash the API post method receives a null value as email.
Please help me how I can successfully pass the '—' without any issue. Thanks in advance.
Based on comments it could be caused by encoding:
client.Encoding = Encoding.UTF8
I need to return the server error from azure functions.
Now I implement the same using InternalServerErrorResult(). It only sends the error code and no response/message can be sent with this function.
How to implement an exception handler where the error code and message can be sent together using actionresult in azure functions
current implementation
catch (Exception ex)
{
log.LogInformation("An error occured {0}" + ex);
//json = new Response(ex.StackTrace, AppConstants.ErrorCodes.SystemException).SerializeToString();
return (ActionResult)new InternalServerErrorResult();
}
this returns with an empty response in postman with error 500
Note that this is from Microsoft.AspNetCore.Mvc namespace:
var result = new ObjectResult(new { error = "your error message here" })
{
StatusCode = 500
};
Based on configured formatters it will return serialized object to client.
For JSON (it's default) it will return following:
{ "error" : "your error message here" }
To send a message with the status code you can use return StatusCode(httpCode, message), which is an ObjectResult.
For example:
return StatusCode(500, "An error occurred");
You can also pass an object (example using HttpStatusCode enum):
return StatusCode((int)HttpStatusCode.InternalServerError, json);
I'm trying to implement a custom error handling in web API,
and I need to get the exception from the returned HttpResponseMessage.
I've tried to get exception info by from:
response.Content.ReadAsAsync<HttpError>().Result
But I can't access the result object, I'm getting an exception when trying,
So I'm obviously doing it wrong.
Can't figure out how to do it,
Assistance would be appreciated.
Edit:
My client code is not relevant, it's simply a GET request, server code:
Controller action throws Exception:
if (condition == true)
{
var response = new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new StringContent("Some Exception Related Message"),
ReasonPhrase = "Some More Info"
};
throw new HttpResponseException(response);
}
SendAsync method of my implemented DelegatingHandler gets the response,
and this is where I want to get the callstack of the exception that was thrown in the controller action above.
errorDetails = new ResponseErrorDetailsFull
{
Message = "An error has occurred.",
ExceptionMessage = response.ReasonPhrase,
StackTrace = response.Content.ReadAsAsync<HttpError>().Result.StackTrace
};
Edit #2
Ok, So I found out that if I create a ExceptionFilterAttribute, and Override OnException(), use the attribute on my DelegatingHandler I'm able to access the exception as mentioned in the above code.
Can someone provide an explanation why this is working this way?
To get HttpError in the response content, your server side API code needs to have written an HttpError instance into the response stream.
Only then response.Content.ReadAsAsync<HttpError>().Result would yield that data.
normally, if a server side code throws an exception, the default behavior is an HTTP 500 (Internal Server Error) status code with nothing parseable in the response message.
In case of HTTP 400 (Bad Request) or other such non-500 (non-200) errors, it is customary to send back response data. (either Validation Errors etc.)
in that case, you may be able to read the data from the response.
in general for any error scenario, unless your server side API code is not writing a known type into the response, you cannot read it off the response on the caller side.
please post your server side and client side code, for us to help you further.
I found this blog with very good example:
http://nodogmablog.bryanhogan.net/2016/07/getting-web-api-exception-details-from-a-httpresponsemessage/
I adopted the code with some updates:
if ((int)response.StatusCode >= 400)
{
exceptionResponse = JsonConvert.DeserializeObject<ExceptionResponse>(LogRequisicao.CorpoResposta);
LogRequisicao.CorpoResposta = exceptionResponse.ToString() ;
if (exceptionResponse.InnerException != null)
LogRequisicao.CorpoResposta += "\r\n InnerException: " + exceptionResponse.ToString();
}
using object:
public class ExceptionResponse
{
public string Message { get; set; }
public string ExceptionMessage { get; set; }
public string ExceptionType { get; set; }
public string StackTrace { get; set; }
public ExceptionResponse InnerException { get; set; }
public override String ToString()
{
return "Message: " + Message + "\r\n "
+ "ExceptionMessage: " + ExceptionMessage + "\r\n "
+ "ExceptionType: " + ExceptionType + " \r\n "
+ "StackTrace: " + StackTrace + " \r\n ";
}
}
My sample code of ApiKey validation is given below (I am using MVC4 web api RC):
public class ApiKeyFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext context)
{
//read api key from query string
string querystring = context.Request.RequestUri.Query;
string apikey = HttpUtility.ParseQueryString(querystring).Get("apikey");
//if no api key supplied, send out validation message
if (string.IsNullOrWhiteSpace(apikey))
{
var response = context.Request.CreateResponse(HttpStatusCode.Unauthorized, new Error { Message = "You can't use the API without the key." });
throw new HttpResponseException(response);
}
else
{
try
{
GetUser(decodedString); //error occurred here
}
catch (Exception)
{
var response = context.Request.CreateResponse(HttpStatusCode.Unauthorized, new Error { Message = "User with api key is not valid" });
throw new HttpResponseException(response);
}
}
}
}
Here problem is with Catch block statement. I Just wanted to send custom error message to user. But nothing is sent. It displays a blank screen
However, the statement below is working well and sends out the validation error message correctly:
if (string.IsNullOrWhiteSpace(apikey))
{
var response = context.Request.CreateResponse(HttpStatusCode.Unauthorized, new Error { Message = "You can't use the API without the key." });
throw new HttpResponseException(response);
}
Is there anything that i am doing wrong.
I was having the same issue in the exact same scenario. However, in this scenario, you need to return some content in your response to be shown and not really throw the exception. So based on this, I would change your code to the following:
catch (Exception)
{
var response = context.Request.CreateResponse(httpStatusCode.Unauthorized);
response.Content = new StringContent("User with api key is not valid");
context.Response = response;
}
So with this change you are now returning your response, with content that will displayed in place of the blank screen.