Gmail API: asynchronous label update/application - gmail

I'm using the Users.messages:modify method to apply labels to emails, however, I must refresh the page before the labels which I apply programmatically appear on the gmail user interface.
The desired action is akin to if I manually select a gmail message and then apply a label from the dropdown label applicator at the top of the gmail screen: the label is applied asynchronously. Is this possible to do programmatically?
Code
var applyLabel = function (gapiRequestURL, labelIdsArr)
{
$.ajax({
url: gapiRequestURL,
method: "POST",
contentType: "application/json",
data: JSON.stringify({
addLabelIds: labelIdsArr
}),
success: function(msg){
// alert(JSON.stringify(msg));
},
error: function(msg){
alert("Error:" + JSON.stringify(msg));
}
})
}
var decideWhichLabelToApply = function(messageContentsArr){
var testLabelOne = "Label_12"
var testLabelTwo = "Label_13"
var labelIdsArr = []
for(var i=0; i < messageContentsArr.length; i++){
var currentMessage = messageContentsArr[i]
var messageID = currentMessage.id
if (true){
var labelModifyURL = "https://www.googleapis.com/gmail/v1/users/me/messages/" + messageID + "/modify?access_token=" + thisToken
labelIdsArr.push(testLabelOne)
applyLabel(labelModifyURL, labelIdsArr)
}
else {
var labelModifyURL = "https://www.googleapis.com/gmail/v1/users/me/messages/" + messageID + "/modify?access_token=" + thisToken
labelIdsArr.push(testLabelTwo)
applyLabel(labelModifyURL, labelIdsArr)
}
}
}

Not that I know of. The Gmail web interface does some lazy caching and doesn't seem to notice particularly well changes to the underlying data (i.e. from Inbox, IMAP, API, etc). I believe it doesn't require a full browser (F5) refresh but certainly one needs to do some UI action like clicking on labels or hitting the in-webpage refresh icon for update to show up.

Related

How to configure the user_token of Damn Vulnerable Web Application within CSRF field while Script based authentication using ZAP?

I had been following the documentation of Script Based Authentication for Damn Vulnerable Web Application using ZAP. I have navigated to http://localhost/dvwa/login.php through Manual Explore which opens up the DVWA application on my localhost as follows:
and adds the URL to the Default Context.
I've also created the dvwa script with the following configuration:
and modified the dvwa script:
Now when I try Configure Context Authentication, dvwa script does gets loaded but the CSRF field doesn't shows up.
Additionally, POST Data doesn't even shows up but Extra POST Data is shown.
Am I missing something in the steps? Can someone help me out?
The modified script within the documentation of Script Based Authentication section for Damn Vulnerable Web Application using ZAP
seems incomplete.
The complete script is available at Setting up ZAP to Test Damn Vulnerable Web App (DVWA) which is as follows:
function authenticate(helper, paramsValues, credentials) {
var loginUrl = paramsValues.get("Login URL");
var csrfTokenName = paramsValues.get("CSRF Field");
var csrfTokenValue = extractInputFieldValue(getPageContent(helper, loginUrl), csrfTokenName);
var postData = paramsValues.get("POST Data");
postData = postData.replace('{%username%}', encodeURIComponent(credentials.getParam("Username")));
postData = postData.replace('{%password%}', encodeURIComponent(credentials.getParam("Password")));
postData = postData.replace('{%' + csrfTokenName + '%}', encodeURIComponent(csrfTokenValue));
var msg = sendAndReceive(helper, loginUrl, postData);
return msg;
}
function getRequiredParamsNames() {
return [ "Login URL", "CSRF Field", "POST Data" ];
}
function getOptionalParamsNames() {
return [];
}
function getCredentialsParamsNames() {
return [ "Username", "Password" ];
}
function getPageContent(helper, url) {
var msg = sendAndReceive(helper, url);
return msg.getResponseBody().toString();
}
function sendAndReceive(helper, url, postData) {
var msg = helper.prepareMessage();
var method = "GET";
if (postData) {
method = "POST";
msg.setRequestBody(postData);
}
var requestUri = new org.apache.commons.httpclient.URI(url, true);
var requestHeader = new org.parosproxy.paros.network.HttpRequestHeader(method, requestUri, "HTTP/1.0");
msg.setRequestHeader(requestHeader);
helper.sendAndReceive(msg);
return msg;
}
function extractInputFieldValue(page, fieldName) {
// Rhino:
var src = new net.htmlparser.jericho.Source(page);
// Nashorn:
// var Source = Java.type("net.htmlparser.jericho.Source");
// var src = new Source(page);
var it = src.getAllElements('input').iterator();
while (it.hasNext()) {
var element = it.next();
if (element.getAttributeValue('name') == fieldName) {
return element.getAttributeValue('value');
}
}
return '';
}
Using this script, CSRF Field and POST Data field shows up just perfect.

Embed an instagram feed

I am looking to simply add a instagram feed onto a cms website - I have got an api code/secret key to use - but the instagram instructions make absolutely no sense. I can see how to embed one post - but not an entire feed (i am not a developer so I donlt understand how to write a get/ombed query - but if I had a code snipper I could change it!)
I just need the code as I presume I can then change this to the relevant instragram account
https://www.instagram.com/developer/embedding/
Here is a link to a good post about how to display an Instagram feed on your website. Parts of the article include javascript, but the author tries to keep it as simple as possible. The main javascript code is:
var request = new XMLHttpRequest();
request.open('GET', 'https://api.instagram.com/v1/users/self/media/recent/?access_token=ENTER-YOUR-ACCESS-TOKEN-HERE&count=8', true);
request.onload = function(container) {
if (request.status >= 200 && request.status < 400) {
// Success!
var data = JSON.parse(request.responseText);
for (var i=0;i < data.data.length;i++) {
var container = document.getElementById('insta-feed');
var imgURL = data.data[i].images.standard_resolution.url;
console.log(imgURL);
var div = document.createElement('div');
div.setAttribute('class','instapic');
container.appendChild(div);
var img = document.createElement('img');
img.setAttribute('src',imgURL)
div.appendChild(img);
}
console.log(data);
} else { }
};
request.onerror = function() {
//There was a connection error of some sort
};
request.send();
This code adds the instagram image to the html div with the id "insta-feed". So you need to add the following html to your page:
<div id="insta-feed"></div>
A similar piece of code using jquery would be:
$.get("https://api.instagram.com/v1/users/self/media/recent/?access_token=ENTER-YOUR-ACCESS-TOKEN-HERE&count=8", function (result) {
var html = "";
for (var i = 0; i < result.data.length; i++) {
html += "<div><img src='" + result.data[i].images.standard_resolution.url + "' /></div>";
}
$("#insta-feed").html(html);
});

Chrome inapp purchase test

I'm trying to implement an inapp purchase for my Chrome Extension. I have followed the guide on https://developer.chrome.com/webstore/payments-iap, added 1 buyable item and implemented following code on an onclick event:
google.payments.inapp.getSkuDetails({
'parameters': {'env': 'prod'},
'success': onSkuDetails,
'failure': onSkuDetailsFail
});
var onSkuDetails = function (response) {
console.log("onSkuDetails", response);
/*var products = response.response.details.inAppProducts;
var count = products.length;
for (var i = 0; i < count; i++) {
var product = products[i];
addProductToUI(product);
}
getLicenses();*/
}
var onSkuDetailsFail = function(result){
console.log("onSkuDetailsFailed", result);
}
But every time I click it, I get
onSkuDetailsFailed > "INVALID_RESPONSE_ERROR"
I have added the buy.js and changed some permissions, but still don't see where the problem might be.
Do note, that I'm testing this extension locally and not from the Chrome webstore using my own account and a friend's account which I included as testperson on the dashboard.

Values seems changing straight after Initial Save in Dynamics CRM Opportunity

I'm doing a Service Call to retrieve the Account details (currency, discount associated with the account) on the Selection of the Account lookup on the Opportunity form (form type == 1 // Create) using Web API in CRM 2016 On-Premise. Everything is working fine but when the opportunity is saved initially it's straight away coming up with unsaved changes next to the Save button after the initial save which is forcing me to do another save(abnormal behaviour).I'm not so sure what value is changing straightaway after initial save.
The Service Call is Synchronous and is being triggered on the change of the Account Lookup, well before the initial save. Any Help Appreciated!.
function SetOpportunityCurrencyAndDiscount(){
var accountId = (GetValue("vm_accountid"))[0].id;
var result = RetrieveRecord("account", null, accountId.slice(1,-1));
var accountDiscount = result["vm_accountdiscount"];
var transactionCurrencyId = result["_transactioncurrencyid_value"];
var currencyName = result["_transactioncurrencyid_value#OData.Community.Display.V1.FormattedValue"];
SetValue("vm_discount", accountDiscount);
Xrm.Page.getAttribute("transactioncurrencyid").setValue([{ id: transactionCurrencyId, name: currencyName, entityType: "transactioncurrency"}]); }
function RetrieveRecord(recordType, alternateKey, accountId){
var result = null;
var entityType = recordType;
var query = null;
if(alternateKey != null && agencyId == null)
query = "/api/data/v8.0/accounts(emailaddress1='"+alternateKey+"')?$select=name,accountid,_transactioncurrencyid_value,vm_agencydiscount";
else
query = "/api/data/v8.0/accounts("+agencyId+")?$select=name,accountid,_transactioncurrencyid_value,vm_agencydiscount";
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + query, false);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"OData.Community.Display.V1.FormattedValue\"");
req.onreadystatechange = function () {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
result = JSON.parse(this.response);
}
else {
alert(this.statusText);
}
}
};
req.send();
return result;
}
After you save your record and the form is dirty again, open dev tools and paste this into the console. It will show you which fields are dirty.
function showDirtyFields() {
var Xrm = Array.prototype.slice.call(document.querySelectorAll('iframe')).filter(function(d) {
return d.style.visibility !== 'hidden';
})[0].contentWindow.Xrm;
var message='The following fields are dirty: \n';
Xrm.Page.data.entity.attributes.forEach(function(attribute,index){
if(attribute.getIsDirty()==true){message+="\u2219 "+attribute.getName()+"\n";}
});
Xrm.Utility.alertDialog(message);
}
showDirtyFields();
Another way of accomplishing the same thing is to turn on auditing for the entity. The audit log will show you which fields were submitted.

Trigger download of file from within Dynamics CRM 2011 Plugin

I have an Entity in Dynamics CRM 2011 where license files are stored in base64-encoded format.
Up until now, the licenses has been delivered by email to the recipient (creating an e-mail activity and adding the file as attachment). I now also want to add the possibility to download the file directly from within Dynamics CRM.
Is there any way for a CRM 2011 Plugin to trigger a download of the file (base64-encoded string) to the client web browser?
I.e. I want the PostLicenseUpdate class / ExecutePostLicenseUpdate function to start/trigger a download of the file.
A very similar problem was solved by creating a separate .aspx on the webserver, however I'd prefer using a built in function i CRM.
Here's my solution to the problem.
Except for jQuery, grab FileSaver.js, Blob.js and base64-binary.js.
Create your own download.js file as below, and add the addRequestDownloadLink-function to the OnLoad event of the form.
As the original license data is binary, you'll need to use Base64-binary.js instead of i.e. atob().
function addRequestDownloadLink() {
$('#my_download').append('<div id="my_download_downloadcontainer">Request download of license file</div>');
}
$('body').on('click', '#my_download_downloadlink', function() {
var str_decoded = Base64Binary.decode($(this).attr('data-license'));
var blob = new Blob([str_decoded], {type: "license/binary"});
saveAs(blob, $(this).attr('data-filename'));
});
$('body').on('click', '#my_download_requestdownload', function() {
var guid = Xrm.Page.data.entity.getId();
guid = guid.replace("{", ""); guid = guid.replace("}", "");
var filename = Xrm.Page.getAttribute("my_name").getValue() + ".dat";
var organization = Xrm.Page.context.getOrgUniqueName();
var entity = "my_license";
var select = "?$select=my_DataSigned"
var oDataSelect = "/" + organization + "/XRMServices/2011/OrganizationData.svc/" + entity + "Set(guid'" + guid + "')" + select;
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: oDataSelect,
beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
success: function (data, textStatus, XmlHttpRequest) {
if (data.d.my_DataSigned != null) {
$('#my_download_downloadcontainer').html('<a href="#" id="my_download_downloadlink" data-license="' + data.d.my_DataSigned + '" data-filename="' + filename + '">Download license file!</span>');
}
else {
alert("No license found!");
}
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus + "; ErrorThrown: " + errorThrown);
}
});
});
Tadaaa! Hope this will help someone with the same issue.
I don't think its possible using Plugins. You can try JavaScript.
Create a Custom button on Ribbon, and edit to run a javascript function on button click. Retrieve the value using OData call and write into a file. Then trigger the download. Have a look at this.
Note: If you are going to use this approach please be careful because there won't be any ribbons in CRM 2013. So in future, you might have to tweak it.

Resources