getAttachmentContentAsync does not return anything - outlook

I've read the documentation over on: https://learn.microsoft.com/en-us/javascript/api/outlook/office.messagecompose?view=outlook-js-preview&preserve-view=true#getComposeTypeAsync_options__callback_ , but nothing has been returned. Not even error messages. It doesn't return anything at all. The code i've used is below:
var item = Office.context.mailbox.item;
var options = {asyncContext: {currentItem: item}};
item.getAttachmentsAsync(options, callback);
function callback(result) {
if (result.value.length > 0) {
for (i = 0 ; i < result.value.length ; i++) {
result.asyncContext.currentItem.getAttachmentContentAsync(result.value[i].id, handleAttachmentsCallback);
}
}
}
function handleAttachmentsCallback(result) {
// Parse string to be a url, an .eml file, a base64-encoded string, or an .icalendar file.
switch (result.value.format) {
case Office.MailboxEnums.AttachmentContentFormat.Base64:
// Handle file attachment.
console.log(result.value.content);
break;
case Office.MailboxEnums.AttachmentContentFormat.Eml:
// Handle email item attachment.
console.log("Attachment is a message.");
break;
case Office.MailboxEnums.AttachmentContentFormat.ICalendar:
// Handle .icalender attachment.
console.log("Attachment is a calendar item.");
break;
case Office.MailboxEnums.AttachmentContentFormat.Url:
// Handle cloud attachment.
console.log("Attachment is a cloud attachment.");
break;
default:
// Handle attachment formats that are not supported.
}
}
I have inserted the code for the MessageCompose form and I know that it requires the v1.8 API. I have tested other methods such as getAttachmentsAsync(options, callback) and they work as expected.
As a test, I have been using console logs at specific points where the code works up to. The console outputs the result of callback(result) as OSF.DDA.AsyncResult where status=succeeded. However, it displays "This value was evaluated upon first expanding. It may have changed since then." and it won't allow me to inspect the Object when you click expand.
Additionally logging result.value[i] in callback works as well, with the same issue where I cant expand the object for more details.
Why won't getAttachmentContentAsync return anything?

Related

How get attachments in outlook plugin?

Hi how can i get attachments and send it to my java server?
in docs its say:
var item = Office.context.mailbox.item;
var options = {asyncContext: {currentItem: item}};
item.getAttachmentsAsync(options, callback);
function callback(result) {
if (result.value.length > 0) {
for (i = 0 ; i < result.value.length ; i++) {
result.asyncContext.currentItem.getAttachmentContentAsync(result.value[i].id, handleAttachmentsCallback);
}
}
}
function handleAttachmentsCallback(result) {
// Parse string to be a url, an .eml file, a base64-encoded string, or an .icalendar file.
switch (result.value.format) {
case Office.MailboxEnums.AttachmentContentFormat.Base64:
// Handle file attachment.
break;
case Office.MailboxEnums.AttachmentContentFormat.Eml:
// Handle email item attachment.
break;
case Office.MailboxEnums.AttachmentContentFormat.ICalendar:
// Handle .icalender attachment.
break;
case Office.MailboxEnums.AttachmentContentFormat.Url:
// Handle cloud attachment.
break;
default:
// Handle attachment formats that are not supported.
}
}
But i have several errors witch this example.
first is item.getAttachmentsAsync is not a function
then im tried to use
result.asyncContext.currentItem.getAttachmentContentAsync(item.attachments[2].id, handleAttachmentsCallback);
but its never called calback
How can i get attachments and send them by XMLHttpRequest to my server?
Most likely what is happening is that you are trying this code on a read item. The getAttachmentsAsync fn only exists in compose mode, so you would see the error above if you are not composing an email. For read emails you should be able to just access the attachments property Office.context.mailbox.item.attachments (https://learn.microsoft.com/en-us/javascript/api/outlook/office.attachmentdetails?view=outlook-js-preview)
Read Mode:
https://learn.microsoft.com/en-us/office/dev/add-ins/outlook/get-attachments-of-an-outlook-item?view=outlook-js-preview
Compose Mode:
https://learn.microsoft.com/en-us/office/dev/add-ins/outlook/add-and-remove-attachments-to-an-item-in-a-compose-form?view=outlook-js-preview
However, as mentioned in Jadams answer, getAttachmentContentAsync IS supported in Read Mode, and you can get that to the the Base64 encoding of attachments. (the first link will be updated soon to reflect this)

Getting file contents when using DropzoneJS

I really love the DropZoneJS component and am currently wrapping it in an EmberJS component (you can see demo here). In any event, the wrapper works just fine but I wanted to listen in on one of Dropzone's events and introspect the file contents (not the meta info like size, lastModified, etc.). The file type I'm dealing with is an XML file and I'd like to look "into" it to validate before sending it.
How can one do that? I would have thought the contents would hang off of the file object that you can pick up on many of the events but unless I'm just missing something obvious, it isn't there. :(
This worked for me:
Dropzone.options.PDFDrop = {
maxFilesize: 10, // Mb
accept: function(file, done) {
var reader = new FileReader();
reader.addEventListener("loadend", function(event) { console.log(event.target.result);});
reader.readAsText(file);
}
};
could also use reader.reaAsBinaryString() if binary data!
Ok, I've answer my own question and since others appear interested I'll post my answer here. For a working demo of this you can find it here:
https://ui-dropzone.firebaseapp.com/demo-local-data
In the demo I've wrapped the Dropzone component in the EmberJS framework but if you look at the code you'll find it's just Javascript code, nothing much to be afraid of. :)
The things we'll do are:
Get the file before the network request
The key thing we need become familiar with is the HTML5 API. Good news is it is quite simple. Take a look at this code and maybe that's all you need:
/**
* Replaces the XHR's send operation so that the stream can be
* retrieved on the client side instead being sent to the server.
* The function name is a little confusing (other than it replaces the "send"
* from Dropzonejs) because really what it's doing is reading the file and
* NOT sending to the server.
*/
_sendIntercept(file, options={}) {
return new RSVP.Promise((resolve,reject) => {
if(!options.readType) {
const mime = file.type;
const textType = a(_textTypes).any(type => {
const re = new RegExp(type);
return re.test(mime);
});
options.readType = textType ? 'readAsText' : 'readAsDataURL';
}
let reader = new window.FileReader();
reader.onload = () => {
resolve(reader.result);
};
reader.onerror = () => {
reject(reader.result);
};
// run the reader
reader[options.readType](file);
});
},
https://github.com/lifegadget/ui-dropzone/blob/0.7.2/addon/mixins/xhr-intercept.js#L10-L38
The code above returns a Promise which resolves once the file that's been dropped into the browser has been "read" into Javascript. This should be very quick as it's all local (do be aware that if you're downloading really large files you might want to "chunk" it ... that's a more advanced topic).
Hook into Dropzone
Now we need to find somewhere to hook into in Dropzone to read the file contents and stop the network request that we no longer need. Since the HTML5 File API just needs a File object you'll notice that Dropzone provides all sorts of hooks for that.
I decided on the "accept" hook because it would give me the opportunity to download the file and validate all in one go (for me it's mainly about drag and dropping XML's and so the content of the file is a part of the validation process) and crucially it happens before the network request.
Now it's important you realise that we're "replacing" the accept function not listening to the event it fires. If we just listened we would still incur a network request. So to **overload* accept we do something like this:
this.accept = this.localAcceptHandler; // replace "accept" on Dropzone
This will only work if this is the Dropzone object. You can achieve that by:
including it in your init hook function
including it as part of your instantiation (e.g., new Dropzone({accept: {...})
Now we've referred to the "localAcceptHandler", let me introduce it to you:
localAcceptHandler(file, done) {
this._sendIntercept(file).then(result => {
file.contents = result;
if(typeOf(this.localSuccess) === 'function') {
this.localSuccess(file, done);
} else {
done(); // empty done signals success
}
}).catch(result => {
if(typeOf(this.localFailure) === 'function') {
file.contents = result;
this.localFailure(file, done);
} else {
done(`Failed to download file ${file.name}`);
console.warn(file);
}
});
}
https://github.com/lifegadget/ui-dropzone/blob/0.7.2/addon/mixins/xhr-intercept.js#L40-L64
In quick summary it does the following:
read the contents of the file (aka, _sendIntercept)
based on mime type read the file either via readAsText or readAsDataURL
save the file contents to the .contents property of the file
Stop the send
To intercept the sending of the request on the network but still maintain the rest of the workflow we will replace a function called submitRequest. In the Dropzone code this function is a one liner and what I did was replace it with my own one-liner:
this._finished(files,'locally resolved, refer to "contents" property');
https://github.com/lifegadget/ui-dropzone/blob/0.7.2/addon/mixins/xhr-intercept.js#L66-L70
Provide access to retrieved document
The last step is just to ensure that our localAcceptHandler is put in place of the accept routine that dropzone supplies:
https://github.com/lifegadget/ui-dropzone/blob/0.7.2/addon/components/drop-zone.js#L88-L95
using the FileReader() solution is working amazingly good for me:
Dropzone.autoDiscover = false;
var dz = new Dropzone("#demo-upload",{
autoProcessQueue:false,
url:'upload.php'
});
dz.on("drop",function drop(e) {
var files = [];
for (var i = 0; i < e.dataTransfer.files.length; i++) {
files[i] = e.dataTransfer.files[i];
}
var reader = new FileReader();
reader.onload = function(event) {
var line = event.target.result.split('\n');
for ( var i = 0; i < line.length; i++){
console.log(line);
}
};
reader.readAsText(files[files.length-1]);

Firefox file downloading process structure figure

For my project, I need to study some info like "FireFox/Gecko file downloading structure overview"(if any), or somewhat "file downloading process flow chart of FireFox/Gecko". I couldn't find something like that in the Internet so far. Is there any info about it? Thanks a lot.
PS: It must include the paths about all file downloading through FireFox browser, which are via the network connection info APIs and file handling APIs, just like "httpOpenRequest" or "DoFileDownload" API(if any).
What would be the Firefox downloading process API paths?? Is there any figure or chart?
Please help me...
You are probably going to need to look at the code to get the information you desire. You will need to build the flowchart yourself.
There are a couple of different ways downloading is done in the code.
If you are talking about a Firefox add-on performing a download, then it is probably being done using Downloads.jsm (although there is an older method for doing so). The source code for that JavaScript module is at resource://gre/modules/Downloads.jsm (This URL is only valid in Firefox). There appear to be several files all located in the jsloader\resource\gre\modules directory within the zip format file called omni.ja in the root of the Firefox distribution. You can just copy that file and change the name to omni.zip and access it as a normal .zip file.
If you are wanting to know how Firefox saves a page when it is requested by the user: It is defined in the context menu with the oncommand value being gContextMenu.saveLink();. saveLink() is defined in: chrome://browser/content/nsContextMenu.js. It does some housekeeping and then calls saveHelper() which is in the same file.
The saveHelper() code is the following:
// Helper function to wait for appropriate MIME-type headers and
// then prompt the user with a file picker
saveHelper: function(linkURL, linkText, dialogTitle, bypassCache, doc) {
// canonical def in nsURILoader.h
const NS_ERROR_SAVE_LINK_AS_TIMEOUT = 0x805d0020;
// an object to proxy the data through to
// nsIExternalHelperAppService.doContent, which will wait for the
// appropriate MIME-type headers and then prompt the user with a
// file picker
function saveAsListener() {}
saveAsListener.prototype = {
extListener: null,
onStartRequest: function saveLinkAs_onStartRequest(aRequest, aContext) {
// if the timer fired, the error status will have been caused by that,
// and we'll be restarting in onStopRequest, so no reason to notify
// the user
if (aRequest.status == NS_ERROR_SAVE_LINK_AS_TIMEOUT)
return;
timer.cancel();
// some other error occured; notify the user...
if (!Components.isSuccessCode(aRequest.status)) {
try {
const sbs = Cc["#mozilla.org/intl/stringbundle;1"].
getService(Ci.nsIStringBundleService);
const bundle = sbs.createBundle(
"chrome://mozapps/locale/downloads/downloads.properties");
const title = bundle.GetStringFromName("downloadErrorAlertTitle");
const msg = bundle.GetStringFromName("downloadErrorGeneric");
const promptSvc = Cc["#mozilla.org/embedcomp/prompt-service;1"].
getService(Ci.nsIPromptService);
promptSvc.alert(doc.defaultView, title, msg);
} catch (ex) {}
return;
}
var extHelperAppSvc =
Cc["#mozilla.org/uriloader/external-helper-app-service;1"].
getService(Ci.nsIExternalHelperAppService);
var channel = aRequest.QueryInterface(Ci.nsIChannel);
this.extListener =
extHelperAppSvc.doContent(channel.contentType, aRequest,
doc.defaultView, true);
this.extListener.onStartRequest(aRequest, aContext);
},
onStopRequest: function saveLinkAs_onStopRequest(aRequest, aContext,
aStatusCode) {
if (aStatusCode == NS_ERROR_SAVE_LINK_AS_TIMEOUT) {
// do it the old fashioned way, which will pick the best filename
// it can without waiting.
saveURL(linkURL, linkText, dialogTitle, bypassCache, false,
doc.documentURIObject, doc);
}
if (this.extListener)
this.extListener.onStopRequest(aRequest, aContext, aStatusCode);
},
onDataAvailable: function saveLinkAs_onDataAvailable(aRequest, aContext,
aInputStream,
aOffset, aCount) {
this.extListener.onDataAvailable(aRequest, aContext, aInputStream,
aOffset, aCount);
}
}
function callbacks() {}
callbacks.prototype = {
getInterface: function sLA_callbacks_getInterface(aIID) {
if (aIID.equals(Ci.nsIAuthPrompt) || aIID.equals(Ci.nsIAuthPrompt2)) {
// If the channel demands authentication prompt, we must cancel it
// because the save-as-timer would expire and cancel the channel
// before we get credentials from user. Both authentication dialog
// and save as dialog would appear on the screen as we fall back to
// the old fashioned way after the timeout.
timer.cancel();
channel.cancel(NS_ERROR_SAVE_LINK_AS_TIMEOUT);
}
throw Cr.NS_ERROR_NO_INTERFACE;
}
}
// if it we don't have the headers after a short time, the user
// won't have received any feedback from their click. that's bad. so
// we give up waiting for the filename.
function timerCallback() {}
timerCallback.prototype = {
notify: function sLA_timer_notify(aTimer) {
channel.cancel(NS_ERROR_SAVE_LINK_AS_TIMEOUT);
return;
}
}
// set up a channel to do the saving
var ioService = Cc["#mozilla.org/network/io-service;1"].
getService(Ci.nsIIOService);
var channel = ioService.newChannelFromURI(makeURI(linkURL));
if (channel instanceof Ci.nsIPrivateBrowsingChannel) {
let docIsPrivate = PrivateBrowsingUtils.isWindowPrivate(doc.defaultView);
channel.setPrivate(docIsPrivate);
}
channel.notificationCallbacks = new callbacks();
let flags = Ci.nsIChannel.LOAD_CALL_CONTENT_SNIFFERS;
if (bypassCache)
flags |= Ci.nsIRequest.LOAD_BYPASS_CACHE;
if (channel instanceof Ci.nsICachingChannel)
flags |= Ci.nsICachingChannel.LOAD_BYPASS_LOCAL_CACHE_IF_BUSY;
channel.loadFlags |= flags;
if (channel instanceof Ci.nsIHttpChannel) {
channel.referrer = doc.documentURIObject;
if (channel instanceof Ci.nsIHttpChannelInternal)
channel.forceAllowThirdPartyCookie = true;
}
// fallback to the old way if we don't see the headers quickly
var timeToWait =
gPrefService.getIntPref("browser.download.saveLinkAsFilenameTimeout");
var timer = Cc["#mozilla.org/timer;1"].createInstance(Ci.nsITimer);
timer.initWithCallback(new timerCallback(), timeToWait,
timer.TYPE_ONE_SHOT);
// kick off the channel with our proxy object as the listener
channel.asyncOpen(new saveAsListener(), null);
}

CI Route Issue Not Getting Variable

I'm having an issue with this route and not sure what my problem is exactly.
My page is located at http://www.kansasoutlawwrestling.com/kowmanager/pmsystem/viewmessage/1 where 1 is the message id.
I set up a route to look like
$route['pmsystem/viewmessage/(:num)'] = 'pmsystem/viewmessage/$1';
and I'm still getting a error message like this
A PHP Error was encountered
Severity: Warning
Message: Missing argument 1 for Pmsystem::viewmessage()
Filename: controllers/pmsystem.php
Line Number: 76
// View A Message
function viewmessage($message_id)
{
//Config Defaults Start
$msgBoxMsgs = array();//msgType = dl, info, warn, note, msg
$cssPageAddons = '';//If you have extra CSS for this view append it here
$jsPageAddons = '<script src='.base_url().'../assets/js/cpanel/personalmessages.js></script><script src='.base_url().'assets/js/mylibs/jwysiwyg/jquery.wysiwyg.js></script>';//If you have extra JS for this view append it here
$metaAddons = '';//Sometimes there is a need for additional Meta Data such in the case of Facebook addon's
$siteTitle = '';//alter only if you need something other than the default for this view.
//Config Defaults Start
//examples of how to use the message box system (css not included).
//$msgBoxMsgs[] = array('msgType' => 'dl', 'theMsg' => 'This is a Blank Message Box...');
/**********************************************************Your Coding Logic Here, Start*/
// Checks to see if a session is active for user and shows corresponding view page
if (!$this->loggedin->chkLoginStatus() === FALSE)
{
if( ! $this->uri->segment(3))
{
redirect('error', 'refresh');
}
}
else
{
redirect('login', 'refresh');
}
$bodyContent = 'viewpm';//which view file
$bodyType = "full";//type of template
/***********************************************************Your Coding Logic Here, End*/
//Double checks if any default variables have been changed, Start.
//If msgBoxMsgs array has anything in it, if so displays it in view, else does nothing.
if(count($msgBoxMsgs) !== 0)
{
$msgBoxes = $this->msgboxes->buildMsgBoxesOutput(array('display' => 'show', 'msgs' =>$msgBoxMsgs));
}
else
{
$msgBoxes = array('display' => 'none');
}
if($siteTitle == '')
{
$siteTitle = $this->metatags->SiteTitle(); //reads
}
//Double checks if any default variables have been changed, End.
$this->data['msgBoxes'] = $msgBoxes;
$this->data['cssPageAddons'] = $cssPageAddons;//if there is any additional CSS to add from above Variable this will send it to the view.
$this->data['jsPageAddons'] = $jsPageAddons;//if there is any addictional JS to add from the above variable this will send it to the view.
$this->data['metaAddons'] = $metaAddons;//if there is any addictional meta data to add from the above variable this will send it to the view.
$this->data['pageMetaTags'] = $this->metatags->MetaTags();//defaults can be changed via models/metatags.php
$this->data['siteTitle'] = $siteTitle;//defaults can be changed via models/metatags.php
$this->data['bodyType'] = $bodyType;
$this->data['bodyContent'] = $bodyContent;
$this->data['user_data'] = $this->users->getUserByUserId($this->session->userdata('user_id'));
$this->data['users'] = $this->loggedin->getUserList();
$this->data['personal_messages'] = array($this->pmmodel->getTotalMessages($this->session->userdata('user_id')), $this->pmmodel->getTotalUnreadMessages($this->session->userdata('user_id')), $this->pmmodel->getLast5Messages($this->session->userdata('user_id')));
$this->data['messages'] = array($this->pmmodel->getInboxMessages($this->session->userdata('user_id')), $this->pmmodel->getSentMessages($this->session->userdata('user_id')));
//$this->data['message_data'] = $this->pmmodel->getPmMessage($this->uri->segment(3));
$this->load->view('cpanel/index', $this->data);
}
UPDATE
// Checks to see if a session is active for user and shows corresponding view page
if (!$this->loggedin->chkLoginStatus() === FALSE)
{
if (!is_numeric($this->uri->segment(3)))
{
$this->data['message_data'] = 'Invalid message id!';
}
else
{
$this->data['message_data'] = $this->pmmodel->getPmMessage($this->uri->segment(3));
}
$bodyContent = 'viewpm';//which view file
}
else
{
redirect('login', 'refresh');
}
$bodyType = "full";//type of template
This route is unnecessary - it doesn't change anything.
$route['pmsystem/viewmessage/(:num)'] = 'pmsystem/viewmessage/$1';
You can remove that route. The problem is here:
function viewmessage($message_id) // no default value means it's required
{
// your code
}
Your controller methods literally accept user input as arguments (whatever's in the address bar). You always have to account for those required arguments not being present in CI controller methods.
function viewmessage($message_id = NULL)
{
if ( ! $message_id) show_404();
// your code
}
This will silence the errors and show a 404 if the required $message_id is not there. Additionally, $this->uri->segment(3) is unnecessary because it should have the same value as $message_id.
I highly discourage redirecting to an error page when you really want a 404, but that's up to you. It sure doesn't help the user realize their mistake when the address is lost after the redirect, and you're sending the wrong HTTP headers by doing so.

How to send large text in AJAX Request using prototype?

I have a situation where I have to send a large text in ajax request using method :POST. I have tried to do like this.
new Ajax.Request(url + "?" + params, {
method: 'post',postBody: {'Test':'Test'}, onSuccess: function (transport) {
switch (transport.responseJSON.Status) {
case "Success":
// alert(transport.responseJSON.Message);
var imgDiv = document.getElementById(control);
imgDiv.style.display = 'none';
break;
case "Failed":
alert(transport.responseJSON.Message);
break;
case "NotAuthorized":
alert(transport.responseJSON.Message);
break;
case "LoginRequired":
window.location = transport.responseJSON.RedirectAfterLogin;
break;
}
}
});
Test in post body will be replaced with large text from a text area. But when I try to access it on server like this
string test = context.Request["Test"];
I get null.
Any solution reference to an example?
Thanks
Write
postbody:'Test=Test'
instead of
postbody: {'Test':'Test'}
As your text is large, so use escape() function so that it is transmitted to server safely. Also be sure that your query string and post body params not clash with each other.
postBody is expected to be a name/value pair like this:
postbody:'Test=Test'
You would also need to add evalJSON = true if you want to use responseJSON assuming your returned content type is actually JSON

Resources