fileAttachment.Load() not working for second attachment - exchangewebservices

I am getting
"The specified object was not found in the store., The process failed to
get the correct properties."
error while loading the FileAttachment.
Here is my code
foreach (Attachment attachment in message.Attachments)
{
if (attachment is FileAttachment)
{
if ( attachment.IsInline==true)
{
// in line image , may be part of signature image not considering for process
continue;
}
else
{
FileAttachment fileAttachment = attachment as FileAttachment;
string route1 = ConfigurationManager.AppSettings["route"];
string route = route1 + fileAttachment.Name;
String strFileUploadResut = "false";
try
{
fileAttachment.Load(route1 + fileAttachment.Name);
FilenetFactory FileNetUploadUtil = new FilenetFactory();
Console.WriteLine(" Sending File " + fileAttachment.Name + " to OneScan webservice.");
}
catch (Exception E)
{
log.logText("Exception during sending to webservice. "+ E.Message, "Info");
if (E.Message.ToString() == "The specified object was not found in the store., The process failed to get the correct properties.")
{ }
For First attachment its load properly. for second attachment i am getting this error. Not sure why its work first time and throws exception second time. What wrong i am doing here? any advice !!

Sounds like it might be another process working on the same message, eg if another process has moved the message between your calls to the server then Id's you have will be invalid and that would be the error you would expect to receive from the server. A way to test that would be to try to load the message after you receive that error.

Related

Can I get the error code from Twilio server response?

I'm using the instructions provided by Twilio to send SMS messages from a Google Sheet. I'm using the UrlFetchApp.fetch(url,params) to make the post request. Currently it's catching any errors and logging it to a cell.
for (i in data) {
var row = data[i];
try {
response_data = sendSms(row[0], row[1]);
status = "Sent";
} catch(err) {
status = "Error";
}
sheet.getRange(startRow + Number(i), 4).setValue(status);
}
The err is quite long Exception: Request failed for https://api.twilio.com/2010-04-01/Accounts/twilio SID/Messages.json returned code 400. Truncated server response: {"code": 21211, "message": "The 'To' number ##### is not a valid phone number.", "more_info": "https://www.twilio.com/docs/errors/21211", "stat... (use muteHttpExceptions option to examine full response).
Is it possible to get just the code value? In the example above, that would be 21211. I'd like to show the user, but in more user friendly language.
I have tried to use the getContentText() as documented but couldn't get it to return anything.

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

Tomcat Restful API 404

GET api/users/1
Here's the situation:
if user 1 does not exist, respond a 404 http status code and a json message.
The json message would like this:
{
"message": "Resouces `api/users/1` does not exist"
"error_code": 1000
}
And here's the code:
if(user == null) {
Map<String, Object> error = new HashMap<String, Object>();
error.put("message", "Resource `api/users/" + id + "` does not exist!");
error.put("error_code", 1000);
return new ResponseEntity<Object>(error, HttpStatus.NOT_FOUND);
}
return new ResponseEntity<Object>(user, HttpStatus.OK);
But tomcat returns a default error page without the response body:
What should I do, if I want a page like below:
Instead of returning error object return custom json object with status codes , or you can use error-page element which specifies mapping between error page and a handler method ,
404
/error
And then in your controller hand that .
Read more here
Instead of using
return new ResponseEntity<Object>(error, HttpStatus.NOT_FOUND);
Use
return new ResponseEntity<Object>(error, HttpStatus.SC_ACCEPTED);
This answer is provided by the OP and is edited out from the question.
Forgetting to add a ResponseBody annotation. Anyway, if declared the controller with the #RestController annotation, it won't be necessary.

POST-Request with JSON Data over HTTPS Connection with Qt5

I'm trying to send a POST request over an HTTPS-Connection via Qt5 to a Web-API, but I keep getting the following error-message:
Failure "Error downloading https://.../login - server replied: BAD REQUEST"
Reply:"{"error_tag": "ARGUMENT_MISSING", "error_code": 19, "error_extra": {"argument": "email"}, "error": "Required argument is missing"}"
It seems like the HTTPS Connection works, but the POST request is faulty...
void connection::sendLoginData(){
QUrl url = QString("https://.../login");
QNetworkRequest req(url);
//Creating the JSON-Data
QJsonDocument json;
QJsonObject data;
data["email"] = QString("a#g.com");
data["password"] = QString("---");
json.setObject(data);
QByteArray jsonPost = QJsonDocument(data).toJson();
req.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json; charset=utf-8"));
req.setHeader(QNetworkRequest::ContentLengthHeader, QByteArray::number(jsonPost.size()));
//Sending the Request
QNetworkReply *reply = manager->post(req,jsonPost);
// Connection via HTTPS
QFile certFile(SSLCERTIFICATE);
certFile.open(QIODevice::ReadOnly);
QSslCertificate cert(&certFile, QSsl::Pem);
QSslSocket * sslSocket = new QSslSocket(this);
sslSocket->addCaCertificate(cert);
QSslConfiguration configuration = sslSocket->sslConfiguration();
configuration.setProtocol(QSsl::TlsV1_2);
sslSocket->setSslConfiguration(configuration);
reply->setSslConfiguration(configuration);
}
this is the Slot which is called when QNetworkReply gets a reply:
void connection::onFinished(QNetworkReply *reply){
if (reply->error() == QNetworkReply::NoError) {
//success
qDebug() << "Success" <<reply->readAll();
delete reply;
}
else {
//failure
qDebug() << "Failure" <<reply->errorString();
qDebug() << "Reply: " << reply->readAll();
delete reply;
}
}
The Signal "finished" of QNetworkReply is of course connected to the "onFinished"-Slot
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
manager = new QNetworkAccessManager;
ui->setupUi(this);
Connector = new connection(ui,manager);
connect(manager,SIGNAL(finished(QNetworkReply*)),Connector,SLOT(onFinished(QNetworkReply*)));
}
Maybe someone of you could tell me what's wrong with the POST-Request? Looking at the Reply of the Server it seems like the JSON-Data is never sent, or somehow formatted in a wrong way...
As you didn't provide the exact URL, I'd suggest you to try to check url.isValid() and url.errorString().
I just had an issue, the code worked fine in Qt 4.8, but in Qt 5.4 all my POST requests got 400 Bad Request reply.
I looked into the TCP dump via Wireshark and found out that the URL was wrong.
In my case url.setPath("api/register"); was the line that caused the problem. It should have been url.setPath("/api/register");
Hope it helps.

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