chrome extension that count the number of times we visit a page - iframe

I'm looking around for an extension that count the number I visit a site daily, and I have edited an extension from store and it work perfectly
But the problem is when I put that site into an iframe, it's not counting anymore, somebody plz take a look and give me some advice here? many thanks
manifest.json
{
"background": {
"persistent": true,
"scripts": [ "jquery.js", "counter.js", "background.js" ]
},
"browser_action": {
"default_icon": "icon.png",
"default_popup": "counter.html"
},
"description": "Counter",
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgrQn46/0KFBVFH0l9mKUXPOns5h0YMQ0isRXkB/GzK1h8JfvILDuxkIC7jbyePzMgbY0b8TO7L7FR3m4qcnPJZemz2yrGnHOkppaOWaAuyJm2cQeOul89qNPsC1GROoKfBmajag5OaOr02y4de3MEKSTubtjlO5crbg8xKnp7nHbqkeIq9MOMsEo0/uOQMqvixMnIAfPamUPOQfqmG2lUeo9UgTUoFBaxpf5VhgcuDcLHnkkSrzRrL0DoYeYFqyXwGmiCdvmwkWF+Eax/+s2xGemqMSUj0mrMxzz8KfoWuAWn9pcXYMEINSelIwS/x+wf+NWWmsCY0pV9yF54+vprQIDAQAB",
"manifest_version": 2,
"name": "counter",
"permissions": [ "tabs", "history", "background", "webNavigation", "http://*/*", "activeTab" ],
"update_url": "https://clients2.google.com/service/update2/crx",
"version": "0.4"
}
counter.js
$(document).ready(function(){
// Display day count
$('.day-count').text(countForToday());
// Display yesterday count
var yesterdayToday = new Date();
var yesterday = new Date(yesterdayToday.setDate(yesterdayToday.getDate() - 1));
var yesterdayString = dateStringForDate(yesterday);
var yesterdayCount = countForDay(yesterdayString);
$('.yesterday-count').text(yesterdayCount);
// Display last 7 days
var weeklyTotal = countForDaysFromToday(7);
$('.week-count').text(weeklyTotal);
// Display last 28 days
var monthlyTotal = countForDaysFromToday(28);
$('.month-count').text(monthlyTotal);
// Total
var total = 0;
for (var i = 0; i < localStorage.length; i++){
var key = localStorage.key(i);
if (key.indexOf("dayCount") > -1) {
var entry = JSON.parse(localStorage.getItem(key));
total += entry.length;
}
}
$('.all-count').text(total);
chrome.browserAction.setBadgeBackgroundColor({ color: '#3BAFDA' });
});
function countForToday() {
// Display day count
var today = new Date();
var todayString = dateStringForDate(today);
var todayCount = countForDay(todayString);
return todayCount;
}
function appendUrlForDay(pageUrl, dateString) {
// get
var currentUrls = urlsForDay(dateString);
// append
var found = false;
for(var i = 0; i < currentUrls.length; i++) {
if (currentUrls[i] == pageUrl) {
found = true;
break;
}
}
if (!found) {
currentUrls.push(pageUrl);
}
// set
localStorage.setItem("dayCount-" + dateString, JSON.stringify(currentUrls));
}
function dateStringForDate(dateObj) {
var month = dateObj.getUTCMonth() + 1;
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
var dateString = year + "/" + month + "/" + day;
return dateString;
}
function countForDaysFromToday(number_of_days) {
console.log(number_of_days);
var total = 0;
for (var i = 0; i < number_of_days; i++) {
var today = new Date();
var dayToLookup = new Date(today.setDate(today.getDate() - i));
var dayString = dateStringForDate(dayToLookup);
var dayCount = countForDay(dayString);
total += dayCount;
}
return total;
}
function urlsForDay(dateString) {
var item = localStorage.getItem("dayCount-" + dateString);
return JSON.parse(item);
}
function countForDay(dateString) {
var currentUrls = urlsForDay(dateString);
if (currentUrls != null) {
return currentUrls.length;
} else {
return 0;
}
}
background.js
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
// Get chrome history
chrome.history.search({text: '', maxResults: 1}, function(data) {
data.forEach(function(page) {
var dateObj = new Date(page.lastVisitTime);
var dateString = dateStringForDate(dateObj);
// Display last page visit
var pageUrl = page.url;
// Set value to 0 on first load
if (localStorage.getItem("dayCount-" + dateString) === null) {
localStorage.setItem("dayCount-" + dateString, JSON.stringify([]));
}
// Check if last page contains mysite.com
if (pageUrl.indexOf("mysite.com") > -1) {
appendUrlForDay(pageUrl, dateString);
}
chrome.browserAction.setBadgeText({ text: countForToday().toString() });
});
});
});

By default, your content script will only run in the top frame of a page. If you want it to run for all frames, you have to set all_frames to true in your manifest.
Google documents this here: https://developer.chrome.com/extensions/content_scripts (just search for all_frames on the page).

Related

sequence of select query not right

I tried to query my database for data. However, when I query for my data, I only managed to get the data after my last alert, which is the alert("Total...") For instance, I run the code below, the alert for "result row:" only appear after the last alert appear. May I know why?
function (result) {
window.location.href = "#/app/CustHomePage";
var totalBalance = 0;
var tableRef = document.getElementById("myList").getElementsByTagName("tbody")[0];
for (var i = 0; i < tableRef.rows.length; i++) {
alert(tableRef.rows[i].cells[3].innerHTML.substr(1));
var addBalance = parseInt(tableRef.rows[i].cells[3].innerHTML.substr(1));
totalBalance = totalBalance + addBalance;
}
alert(totalBalance);
var myText = result.text;
var myTextTwo = myText.replace(/['"]+/g, '');
alert(myTextTwo);
var custBal;
var myDB = window.sqlitePlugin.openDatabase({ name: "mySQLite.db", location: 'default' });
alert("Hello");
myDB.transaction(function(transaction) {
alert("Hello");
transaction.executeSql("SELECT customerBalance FROM customer where nric = '" + myTextTwo + "'", [], function (tx, results) {
var len = results.rows.length;
for (var i = 0; i < len; i++) {
custBal = results.rows.item(i).customerBalance;
alert("result row" + results.rows.item(i).customerBalance);
alert("CustomerBal" + custBal);
}
},
function(tx, error)
{
}
);
});
alert("Total after entitled discount: ");
alert("Transaction successful, Next Customer Please");
}
Move anything you want to happen after the DB transaction has returned or failed in either the success or error handlers, I just moved them out of the arguments and gave them names to keep track of them. and then added your comment to the end of the successCallback handler. Anything you want to happen after a transaction was not successful use the error callback.
function successCallback(tx, results) {
var len = results.rows.length;
for (var i = 0; i < len; i++) {
custBal = results.rows.item(i).customerBalance;
alert("result row" + results.rows.item(i).customerBalance);
alert("CustomerBal" + custBal);
}
alert("Total after entitled discount: ");
alert("Transaction successful, Next Customer Please");
}
function errorCallback(tx, error) {
}
myDB.transaction(function (transaction) {
alert("Hello");
transaction.executeSql("SELECT customerBalance FROM customer where nric = '" + myTextTwo + "'", [], successCallback, errorCallback);
});

SoundManager 2 Slider UI while sliding not changing anything - Wordpress

I have a problem with plugin SoundManager + Slider jquery UI - this one works as volume/current position changer while playing music.
After page is loaded, sometimes (i think it depends on file size) volume and current position are works fine, but if file are too huge, slider is loading properly (no errors in console) but not changing anything.
<?php
// In page Javascript
function audio_player_javascript () {
?>
<script>
var AudioPlayerDebugMode = true;
var songPlays = 0;
function AudioPlayerConsole (message) {
if (AudioPlayerDebugMode == true)
console.log(message);
}
function convertMilliseconds (ms, p) {
var pattern = p || "hh:mm:ss",
arrayPattern = pattern.split(":"),
clock = [ ],
hours = Math.floor ( ms / 3600000 ), // 1 Hour = 36000 Milliseconds
minuets = Math.floor (( ms % 3600000) / 60000), // 1 Minutes = 60000 Milliseconds
seconds = Math.floor ((( ms % 360000) % 60000) / 1000) // 1 Second = 1000 Milliseconds
// build the clock result
function createClock(unit){
// match the pattern to the corresponding variable
if (pattern.match(unit)) {
if (unit.match(/h/)) {
addUnitToClock(hours, unit);
}
if (unit.match(/m/)) {
addUnitToClock(minuets, unit);
}
if (unit.match(/s/)) {
addUnitToClock(seconds, unit);
};
}
}
function addUnitToClock(val, unit){
if ( val < 10 && unit.length === 2) {
val = "0" + val;
}
clock.push(val); // push the values into the clock array
}
// loop over the pattern building out the clock result
for ( var i = 0, j = arrayPattern.length; i < j; i ++ ){
createClock(arrayPattern[i]);
}
return {
hours : hours,
minuets : minuets,
seconds : seconds,
clock : clock.join(":")
};
}
<?php
$detect = new Mobile_Detect();
if ($detect->isMobile())
{
?>
setTimeout(function () {jQuery(".audio-player-toggle").trigger("click");}, 1000);
<?php
}
if (get_option("audio_player_autoplay_plugin") == "yes")
{
?>
setTimeout(function () { jQuery("#play-pause-button").trigger("click"); }, 1000);
<?php
}
?>
jQuery(function() {
soundManager.url = "<?php echo plugins_url('/js/soundmanager/swf', __FILE__);?>";
// Hide audio player
jQuery(".audio-player-toggle.open").live("click", function (e) {
jQuery(".audio-player-container").animate({
bottom: '-' + jQuery(".audio-player-container").height() + 'px'
}, 300, function () {
jQuery(".audio-player-toggle").removeClass("open");
jQuery(".audio-player-toggle").addClass("closed");
});
});
// Show audio player
jQuery(".audio-player-toggle.closed").live("click", function (e) {
jQuery(".audio-player-container").animate({
bottom: '0px'
}, 300, function () {
jQuery(".audio-player-toggle").removeClass("closed");
jQuery(".audio-player-toggle").addClass("open");
});
});
jQuery( "#position-scrubber" ).slider({
range: "max",
min: 0,
max: 0,
value: 0,
slide: function( event, ui ) {
}
});
if (navigator.mimeTypes ["application/x-shockwave-flash"] != undefined)
{
// Set volume range if browser has Flash enabled
jQuery( "#volume-scrubber" ).slider({
range: "max",
min: 0,
max: 100,
value: 50,
slide: function( event, ui ) {
}
});
}
else
{
// Set volume range if browser doesn't have Flash enabled
jQuery( "#volume-scrubber" ).slider({
range: "max",
min: 0,
max: 1,
value: 0.5,
step: 0.01,
slide: function( event, ui ) {
}
});
}
jQuery(".audio-controls-container a").click(function (e) {
e.preventDefault();
});
var htmlSound = new Audio ();
// Set first song in playlist to be played
jQuery(".playlist_item:first").addClass("current");
var firstSong;
var mySound;
// Find playlist item with current class
firstSong = jQuery(".playlist_item:first").attr("data-song_file");
jQuery("#play-pause-button").live("click", function (e) {
AudioPlayerConsole(songPlays);
if (songPlays == 0)
{
playAudio(firstSong);
jQuery(this).addClass("playing");
}
else
{
// Pause music if it has playing class
if (jQuery(this).hasClass("playing"))
{
AudioPlayerConsole("stop playing");
jQuery(this).removeClass("playing");
if (navigator.mimeTypes["application/x-shockwave-flash"] != undefined)
mySound.pause('audio-player');
else
htmlSound.pause();
return;
}
else
{
AudioPlayerConsole("start playing");
jQuery(this).addClass("playing");
if (navigator.mimeTypes ["application/x-shockwave-flash"] != undefined)
mySound.resume('audio-player');
else
htmlSound.play();
return;
}
}
});
jQuery("#next-button").live("click", function (e) {
var thisSongFile = jQuery(".playlist_item.current").next(".playlist_item").attr("data-song_file");
if(!thisSongFile)
{
jQuery(".playlist_item").removeClass("current");
jQuery(".playlist_item:first").addClass("current");
thisSongFile = jQuery(".playlist_item:first").attr("data-song_file");
playAudio(thisSongFile);
}
else
{
console.log(thisSongFile);
var foundCurrent = false;
jQuery(".playlist_item").each(function () {
if (foundCurrent == true)
{
jQuery(this).addClass("current");
foundCurrent = false;
return;
}
if (jQuery(this).hasClass("current"))
{
jQuery(this).removeClass("current");
foundCurrent = true;
}
});
playAudio(thisSongFile);
}
});
jQuery("#previous-button").live("click", function (e) {
var thisSongFile = jQuery(".playlist_item.current").prev(".playlist_item").attr("data-song_file");
if(!thisSongFile)
{
jQuery(".playlist_item").removeClass("current");
jQuery(".playlist_item:first").addClass("current");
thisSongFile = jQuery(".playlist_item:first").attr("data-song_file");
playAudio(thisSongFile);
}
else
{
var foundCurrent = false;
jQuery(".playlist_item").each(function () {
if (jQuery(this).hasClass("current"))
{
jQuery(this).removeClass("current");
jQuery(this).prev(".playlist_item").addClass("current");
}
});
playAudio(thisSongFile);
}
});
// Load album track preview into audio player
jQuery(".track-preview").live("click", function (e) {
e.preventDefault();
var thisSongFile = jQuery(this).attr("data-song_file");
var thisSongArtist = jQuery(this).attr("data-song_artist");
var thisSongTitle = jQuery(this).attr("data-song_title");
var isInPlaylist = false;
// Determine if selected song is already in playlist
jQuery(".playlist_item").each(function () {
// Get title and artist of playing song
var songTitle = jQuery(this).attr("data-song_title");
var songArtist = jQuery(this).attr("data-song_artist");
if (thisSongArtist == songArtist && thisSongTitle == songTitle)
{
jQuery(".playlist_item").removeClass("current");
jQuery(this).addClass("current");
isInPlaylist = true;
}
});
if (isInPlaylist == true)
{
playAudio(thisSongFile);
}
else
{
jQuery(".playlist_item").removeClass("current");
var newPlaylistItem = '<li class="playlist_item current" song_title="' + thisSongTitle + '" song_artwork="" song_file="' + thisSongFile + '" song_artist="' + thisSongArtist + '"></li>';
jQuery("#audio-player-playlist").append(newPlaylistItem);
playAudio(thisSongFile);
}
});
function playAudio (songFile) {
songPlays++;
AudioPlayerConsole("Loading " + songFile);
if (navigator.mimeTypes ["application/x-shockwave-flash"] != undefined)
{
soundManager.onready(function() {
soundManager.destroySound('audio-player');
mySound = soundManager.createSound({
id:'audio-player',
url: songFile,
onload: function() {
var duration = mySound.duration;
jQuery( "#position-scrubber" ).slider("option", "max", duration);
var durationTime = convertMilliseconds(duration, "mm:ss");
jQuery("#total-track-time").html(durationTime.clock);
jQuery( "#position-scrubber" ).bind( "slide", function(event, ui) {
mySound.setPosition(ui.value);
});
// Show pause button
jQuery("#play-pause-button").addClass("playing");
},
whileplaying: function() {
var position = mySound.position;
var positionTime = convertMilliseconds(position, "mm:ss");
jQuery("#current-track-time").html(positionTime.clock);
jQuery( "#position-scrubber" ).slider("option", "value", position/1000);
var volume = jQuery( "#volume-scrubber" ).slider("option", "value");
mySound.setVolume(volume);
},
whileloading: function() {
var duration = mySound.duration;
var durationTime = convertMilliseconds(duration, "mm:ss");
jQuery("#total-track-time").html(durationTime.clock);
},
onfinish: function() {
// Play next song in playlist
setTimeout(function () {jQuery("#next-button").trigger("click");}, 300);
}
});
// End soundManager.createSound
mySound.play();
});
jQuery("#play-pause-button").addClass("playing");
}
// End if (navigator.mimeTypes ["application/x-shockwave-flash"] != undefined)
else
// Player will use HTML5
{
htmlSound.src = songFile;
htmlSound.load();
jQuery( "#position-scrubber" ).bind( "slide", function(event, ui) {
htmlSound.currentTime = ui.value;
});
htmlSound.addEventListener("timeupdate", function() {
var newVolume = jQuery( "#volume-scrubber" ).slider("option", "value");
htmlSound.volume = newVolume;
var duration = htmlSound.duration * 1000;
var durationTime = convertMilliseconds(duration, "mm:ss");
jQuery("#total-track-time").html(durationTime.clock );
var position = htmlSound.currentTime * 1000;
var positionTime = convertMilliseconds(position, "mm:ss");
jQuery("#current-track-time").html(positionTime.clock );
jQuery( "#position-scrubber" ).slider("option", "max", duration/1000);
jQuery( "#position-scrubber" ).slider("option", "value", position/1000);
});
htmlSound.addEventListener("ended", function() {
setTimeout(function () {jQuery("#next-button").trigger("click");}, 300);
});
htmlSound.play();
jQuery("#play-pause-button").addClass("playing");
}
// End Player will use HTML5
jQuery(".playlist_item").each(function () {
if (jQuery(this).hasClass("current"))
{
// Set title, artist, and artwork of playing song
var songArtwork = jQuery(this).attr("data-song_artwork");
var songTitle = jQuery(this).attr("data-song_title");
var songArtist = jQuery(this).attr("data-song_artist");
if (songArtwork != "")
{
jQuery(".audio-player-artwork img").attr("src", songArtwork);
jQuery(".audio-player-artwork").show();
}
else
{
jQuery(".audio-player-artwork img").attr("src", "");
jQuery(".audio-player-artwork").hide();
}
jQuery(".audio-player-song-title").html(songTitle);
jQuery(".audio-player-song-artist").html(songArtist);
}
});
}
// End playAudio()
});
</script>

On Approval Of Quotation, Run Report, Generate PDF and Send an Email With PDF as attachment

I am using CRM ONLINE 2013.
How to automate below process?
On Approval Of Quotation, Run Report.
Generate PDF.
Send an Email With PDF as attachment.
As I have gone through many forums for this topic, but creating a plugin code for generating Report PDF is not possible in CRM ONLINE.
What is the alternate way to do this..?
I have tried below code and it is working fine for me.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript">
if (typeof (SDK) == "undefined")
{ SDK = { __namespace: true }; }
SDK.JScriptRESTDataOperations = {
_context: function () {
if (typeof GetGlobalContext != "undefined")
{ return GetGlobalContext(); }
else {
if (typeof Xrm != "undefined") {
return Xrm.Page.context;
}
else { return new Error("Context is not available."); }
}
},
_getServerUrl: function () {
var serverUrl = this._context().getServerUrl()
if (serverUrl.match(/\/$/)) {
serverUrl = serverUrl.substring(0, serverUrl.length - 1);
}
return serverUrl;
},
_ODataPath: function () {
return this._getServerUrl() + "/XRMServices/2011/OrganizationData.svc/";
},
_errorHandler: function (req) {
return new Error("Error : " +
req.status + ": " +
req.statusText + ": " +
JSON.parse(req.responseText).error.message.value);
},
_dateReviver: function (key, value) {
var a;
if (typeof value === 'string') {
a = /Date\(([-+]?\d+)\)/.exec(value);
if (a) {
return new Date(parseInt(value.replace("/Date(", "").replace(")/", ""), 10));
}
}
return value;
},
Create: function (object, type, successCallback, errorCallback) {
var req = new XMLHttpRequest();
req.open("POST", this._ODataPath() + type + "Set", true);
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.onreadystatechange = function () {
if (this.readyState == 4 /* complete */) {
if (this.status == 201) {
successCallback(JSON.parse(this.responseText, SDK.JScriptRESTDataOperations._dateReviver).d);
}
else {
errorCallback(SDK.JScriptRESTDataOperations._errorHandler(this));
}
}
};
req.send(JSON.stringify(object));
},
Retrieve: function (id, type, successCallback, errorCallback) {
var req = new XMLHttpRequest();
req.open("GET", this._ODataPath() + type + "Set(guid'" + id + "')", true);
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.onreadystatechange = function () {
if (this.readyState == 4 /* complete */) {
if (this.status == 200) {
successCallback(JSON.parse(this.responseText, SDK.JScriptRESTDataOperations._dateReviver).d);
}
else {
errorCallback(SDK.JScriptRESTDataOperations._errorHandler(this));
}
}
};
req.send();
},
Update: function (id, object, type, successCallback, errorCallback) {
var req = new XMLHttpRequest();
req.open("POST", this._ODataPath() + type + "Set(guid'" + id + "')", true);
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("X-HTTP-Method", "MERGE");
req.onreadystatechange = function () {
if (this.readyState == 4 /* complete */) {
if (this.status == 204 || this.status == 1223) {
successCallback();
}
else {
errorCallback(SDK.JScriptRESTDataOperations._errorHandler(this));
}
}
};
req.send(JSON.stringify(object));
},
Delete: function (id, type, successCallback, errorCallback) {
var req = new XMLHttpRequest();
req.open("POST", this._ODataPath() + type + "Set(guid'" + id + "')", true);
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("X-HTTP-Method", "DELETE");
req.onreadystatechange = function () {
if (this.readyState == 4 /* complete */) {
if (this.status == 204 || this.status == 1223) {
successCallback();
}
else {
errorCallback(SDK.JScriptRESTDataOperations._errorHandler(this));
}
}
};
req.send();
},
RetrieveMultiple: function (type, filter, successCallback, errorCallback) {
if (filter != null) {
filter = "?" + filter;
}
else { filter = ""; }
var req = new XMLHttpRequest();
req.open("GET", this._ODataPath() + type + "Set" + filter, true);
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.onreadystatechange = function () {
if (this.readyState == 4 /* complete */) {
if (this.status == 200) {
successCallback(JSON.parse(this.responseText, SDK.JScriptRESTDataOperations._dateReviver).d.results);
}
else {
errorCallback(SDK.JScriptRESTDataOperations._errorHandler(this));
}
}
};
req.send();
},
__namespace: true
};
</script>
<script type="text/javascript">
//Create Email and link it with Order as Regarding field
var Xrm;
var email = new Object();
var ownerID = "";
var CustomerId = "";
if (window.opener) { Xrm = window.opener.Xrm; }
else if (window.parent) { Xrm = window.parent.Xrm; }
//Get ownerid who send email of quotation to customer
function GetOwnerID() {
var owner = Xrm.Page.getAttribute("ownerid").getValue();
ownerID = owner[0].id;
var ownerName = owner[0].name;
var entityType = owner[0].entityType;
GetToEmailGUID();
}
//Get customerid who receive email of quotation from owner
function GetToEmailGUID() {
var Customer = Xrm.Page.getAttribute('customerid').getValue();
CustomerId = Customer[0].id;
var CustomerName = Customer[0].name;
var entityType = Customer[0].entityType;
//if CustomerId is type of "Account" then get Primary Contact id of that account
if (entityType == "account") {
var contact = Xrm.Page.getAttribute("customerid").getValue();
if (contact === null) return;
var serverUrl = Xrm.Page.context.getClientUrl();
var oDataSelect = serverUrl + "/XRMServices/2011/OrganizationData.svc/AccountSet(guid'" + contact[0].id + "')?$select=PrimaryContactId";
var req = new XMLHttpRequest();
req.open("GET", oDataSelect, false);
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json;charset=utf-8");
req.onreadystatechange = function () {
if (req.readyState === 4) {
if (req.status === 200) {
var retrieved = JSON.parse(req.responseText).d;
CustomerId = retrieved.PrimaryContactId.Id;
}
else {
alert(this.statusText);
}
}
};
req.send();
}
}
function CreateEmail() {
GetOwnerID();
email.Subject = "Email with Report Attachment";
//Set The current order as the Regarding object
email.RegardingObjectId = {
Id: Xrm.Page.data.entity.getId(), //Get the current entity Id , here OrderId
LogicalName: Xrm.Page.data.entity.getEntityName()//Get the current entity name, here it will be “salesOrder”
};
//Create Email Activity
SDK.JScriptRESTDataOperations.Create(email, "Email", EmailCallBack, function (error) { alert(error.message); });
}
// Email Call Back function
function EmailCallBack(result) {
email = result; // Set the email to result to use it later in email attachment for retrieving activity Id
var activityPartyFrom = new Object();
// Set the From party of the ActivityParty to relate an entity with Email From field
activityPartyFrom.PartyId = {
Id: CustomerId, //"79EBDD26-FDBE-E311-8986-D89D6765B238", // id of entity you want to associate this activity with.
LogicalName: "contact"
};
// Set the "activity" of the ActivityParty
activityPartyFrom.ActivityId = {
Id: result.ActivityId,
LogicalName: "email"
};
// Now set the participation type that describes the role of the party on the activity).
activityPartyFrom.ParticipationTypeMask = { Value: 2 }; // 2 means ToRecipients
// Create the from ActivityParty for the email
SDK.JScriptRESTDataOperations.Create(activityPartyFrom, "ActivityParty", ActivityPartyFromCallBack, function (error) { alert(error.message); });
var activityPartyTo = new Object();
// Set the From party of the ActivityParty to relate an entity with Email From field
activityPartyTo.PartyId = {
Id: ownerID, //"79EBDD26-FDBE-E311-8986-D89D6765B238", // id of entity you want to associate this activity with.
LogicalName: "systemuser"
};
// Set the "activity" of the ActivityParty
activityPartyTo.ActivityId = {
Id: result.ActivityId,
LogicalName: "email"
};
// Now set the participation type that describes the role of the party on the activity).
activityPartyTo.ParticipationTypeMask = { Value: 1 }; // 1 means Sender
// Create the from ActivityParty
SDK.JScriptRESTDataOperations.Create(activityPartyTo, "ActivityParty", ActivityPartyToCallBack, function (error) { alert(error.message); });
}
//ActivityParty From Callback
function ActivityPartyFromCallBack(result) {
}
//ActivityParty To Callback
function ActivityPartyToCallBack(result) {
GetReportId('Quotation');
}
//Create attachment for the created email
function CreateEmailAttachment() {
//get reporting session and use the params to convert a report in PDF
var params = getReportingSession();
//Email attachment parameters
var activitymimeattachment = Object();
activitymimeattachment.ObjectId = Object();
activitymimeattachment.ObjectId.LogicalName = "email";
activitymimeattachment.ObjectId.Id = email.ActivityId;
activitymimeattachment.ObjectTypeCode = "email",
activitymimeattachment.Subject = "File Attachment";
activitymimeattachment.Body = encodePdf(params);
activitymimeattachment.FileName = "Report.pdf";
activitymimeattachment.MimeType = "application/pdf";
//Attachment call
SDK.JScriptRESTDataOperations.Create(activitymimeattachment, "ActivityMimeAttachment", ActivityMimeAttachmentCallBack, function (error) { alert(error.message); });
}
//ActivityMimeAttachment CallBack function
function ActivityMimeAttachmentCallBack(result) {
var features = "location=no,menubar=no,status=no,toolbar=no,resizable=yes";
var width = "800px";
var height = "600px";
window.open(Xrm.Page.context.getServerUrl() + "main.aspx?etc=" + 4202 + "&pagetype=entityrecord&id=" + email.ActivityId, "_blank", features);
// To open window which works in outlook and IE both
//openStdWin(Xrm.Page.context.getServerUrl() + "main.aspx?etc=" + 4202 + "&pagetype=entityrecord&id=" + email.ActivityId, "_blank", width, height, features);
}
//This method will get the reportId based on a report name that will be used in getReportingSession() function
function GetReportId(reportName) {
var oDataSetName = "ReportSet";
var columns = "ReportId";
var filter = "Name eq '" + reportName + "'";
retrieveMultiple(oDataSetName, columns, filter, onSuccess);
}
function retrieveMultiple(odataSetName, select, filter, successCallback) {
var serverUrl = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var odataUri = serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "?";
if (select) {
odataUri += "$select=" + select + "&";
}
if (filter) {
odataUri += "$filter=" + filter;
}
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: odataUri,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data) {
if (successCallback) {
if (data && data.d && data.d.results) {
successCallback(data.d.results);
}
else if (data && data.d) {
successCallback(data.d);
}
else {
successCallback(data);
}
}
},
error: function (XmlHttpRequest, errorThrown) {
if (XmlHttpRequest && XmlHttpRequest.responseText) {
alert("Error while retrieval ; Error – " + XmlHttpRequest.responseText);
}
}
});
}
function onSuccess(data) {
reportId = data[0].ReportId.replace('{', ").replace('}', ");
CreateEmailAttachment(); // Create Email Attachment
}
//Gets the report contents
function getReportingSession() {
var pth = Xrm.Page.context.getServerUrl() + "/CRMReports/rsviewer/reportviewer.aspx";
var retrieveEntityReq = new XMLHttpRequest();
var Id = Xrm.Page.data.entity.getId();
var quotationGUID = Id.replace('{', ""); //set this to selected quotation GUID
quotationGUID = quotationGUID.replace('}', "");
var reportName = "Quotation"; //set this to the report you are trying to download
var reportID = "7C39D18F-1DC6-E311-8986-D89D6765B238"; //set this to the guid of the report you are trying to download
var rptPathString = ""; //set this to the CRMF_Filtered parameter
var strParameterXML = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'><entity name='quote'><all-attributes /><filter type='and'><condition attribute='quoteid' operator='eq' uitype='quote' value='" + quotationGUID + "' /> </filter></entity></fetch>";
retrieveEntityReq.open("POST", pth, false);
retrieveEntityReq.setRequestHeader("Accept", "*/*");
retrieveEntityReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
rptPathString = "id=%7B" + reportID + "%7D&uniquename=" + Xrm.Page.context.getOrgUniqueName() + "&iscustomreport=true&reportnameonsrs=&reportName=" +
reportName + "&isScheduledReport=false&p:CRMAF_Filteredquote=" + strParameterXML;
//remove the part starting from &p:salesorderid if your report has no parameters
retrieveEntityReq.send(rptPathString);
var x = retrieveEntityReq.responseText.indexOf("ReportSession=");
var ret = new Array();
ret[0] = retrieveEntityReq.responseText.substr(x + 14, retrieveEntityReq.responseText.indexOf("&", x) - x - 14); //the session id
x = retrieveEntityReq.responseText.indexOf("ControlID=");
ret[1] = retrieveEntityReq.responseText.substr(x + 10, retrieveEntityReq.responseText.indexOf("&", x) - x - 10); //the control id
return ret;
}
var bdy = new Array();
var bdyLen = 0;
function concat2Bdy(x) {
bdy[bdyLen] = x;
bdyLen++;
}
function encodePdf(params) {
bdy = new Array();
bdyLen = 0;
var retrieveEntityReq = new XMLHttpRequest();
var pth = Xrm.Page.context.getServerUrl() + "/Reserved.ReportViewerWebControl.axd?ReportSession=" + params[0] +
"&Culture=1033&CultureOverrides=True&UICulture=1033&UICultureOverrides=True&ReportStack=1&ControlID=" + params[1] +
"&OpType=Export&FileName=Public&ContentDisposition=OnlyHtmlInline&Format=PDF";
retrieveEntityReq.open("GET", pth, false);
retrieveEntityReq.setRequestHeader("Accept", "*/*");
retrieveEntityReq.send();
BinaryToArray(retrieveEntityReq.responseBody);
return encode64(bdy);
}
var StringMaker = function () {
this.parts = [];
this.length = 0;
this.append = function (s) {
this.parts.push(s);
this.length += s.length;
}
this.prepend = function (s) {
this.parts.unshift(s);
this.length += s.length;
}
this.toString = function () {
return this.parts.join('');
}
}
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
function encode64(input) {
var output = new StringMaker();
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
while (i < input.length) {
chr1 = input[i++];
chr2 = input[i++];
chr3 = input[i++];
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output.append(keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4));
}
return output.toString();
}
</script>
<script type="text/vbscript">
Function BinaryToArray(Binary)
Dim i
ReDim byteArray(LenB(Binary))
For i = 1 To LenB(Binary)
byteArray(i-1) = AscB(MidB(Binary, i, 1))
concat2Bdy(AscB(MidB(Binary, i, 1)))
Next
BinaryToArray = byteArray
End Function
</script>
</head>
<body>
<input type="button" onclick="CreateEmail();" value="Attach Report" />
</body>
</html>

How do I test to see if a doc exists based off of a date field?

I have a Template helper that attempting to return the current "Day" from the database. What's happening is that even though the current day or date exists in the database, for some reason my helper doesn't see that and creates another date.
client:
Template.days.helpers({
day: function() {
console.log("day called");
var now = new Date();
var month = now.getUTCMonth();
var day = now.getUTCDate();
var year = now.getUTCFullYear();
var bottomRangeDate = new Date(year, month, day);
var topRangeDate = new Date(year, month, day + 1);
// console.log('bottomRangeDate', bottomRangeDate);
// console.log('topRangeDate', topRangeDate);
var currentDay = Days.findOne({"date": {"$gte": bottomRangeDate, "$lt": topRangeDate }});
// console.log(currentDay);
if (currentDay !== undefined) {
// console.log("current day exists");
Session.set('currentDayId', currentDay._id);
return currentDay;
} else {
// console.log('current day is undefined');
Meteor.call('createDay', now, function(error, result) {
if(!error)
Session.set('currentDayId', result);
});
// console.log("current day does not exist");
}
}
});
server:
Meteor.methods({
createDay: function(date) {
console.log("date ", date);
var dayId = Days.insert({
date: date
});
return dayId;
}
});
So what I need to do is to see if today or "date" exists in the database, and if it does return it. If does not, I need to create it.
Edit
Here's a screen shot console after refreshing the browser and call find().fetch() on the collection.
Edit #2
I changed the code up a little to try and get it to work with moment:
Template.days.helpers({
day: function() {
var bottomRangeDate = moment().startOf('day').toDate();
var topRangeDate = moment().endOf('day').toDate();
var now = new Date();
console.log('bottomRangeDate: ', bottomRangeDate);
console.log('topRangeDate: ', topRangeDate);
var currentDay = Days.findOne({"date": {"$gte": bottomRangeDate, "$lt": topRangeDate }});
if (currentDay !== undefined) {
Session.set('currentDayId', currentDay._id);
return currentDay;
} else {
Meteor.call('createDay', now, function(error, result) {
if(!error) {
Session.set('currentDayId', result);
return Days.findOne({_id: result });
}
});
}
}
});
I'm still getting duplicates:

JW Player playlist only loads randomly in IE, works fine in FF every time

The playlist loads every time in FF but only the first time in IE (6-8), after that only randomly.
If I alert the error that's thrown I get "TypeError: playerReady is undefined".
My code looks good and obviously works since FF displays the playlist perfectly. I've got no idea how to solve this. Anyone?
<script type='text/javascript'>
var so = new SWFObject('/UI/Flash/player.swf', 'ply', '<%=FlashWidth %>', '<%=FlashHeight %>', '9', '#ffffff'),
playlistURL = '<%=PlaylistURL %>',
imageURL = '<%=GetBackgroundImageUrl() %>';
so.addParam('allowfullscreen', 'true');
so.addParam('allowscriptaccess', 'always');
if (playlistURL !== '') {
so.addVariable('playlistfile', playlistURL);
so.addVariable('playlist', 'none');
so.addVariable('enablejs', 'true');
}
else {
so.addVariable('file', '<%=FlashURL %>');
}
if (imageURL.length > 0) {
so.addVariable('image', imageURL);
}
so.write('preview<%=PlayerID %>');
</script>
The playerReady function is called by the player once it's finished it's setup process. Do you happen to define that function and then set it to undefined? That might cause an error.
Also, what version of the player are you using?
so.addVariable('enablejs', 'true');
I don't belive that's been a flashvar since the 3.X player, which is no longer supported.
Best,
Zach
Developer, LongTail Video
Not sure how I solved it, but here is the final code that actually works:
HTML PAGE:
<script type='text/javascript'>
var so = new SWFObject('/UI/Flash/player.swf', 'ply', '700', '345', '9', '#ffffff'),
playlistUrl = 'XML-PLaylist',
imageURL = '/ImageVault/Images/conversionFormat_2/id_1577/scope_0/ImageVaultHandler.aspx';
so.addParam('allowfullscreen', 'true');
so.addParam('allowscriptaccess', 'always');
so.addParam('wmode', 'opaque');
if (playlistUrl !== '') {
so.addVariable('playlistfile', playlistUrl);
so.addVariable('playlist', 'none');
so.addVariable('controlbar', 'bottom');
so.addVariable('backcolor', '0xDDE5FF');
so.addVariable('frontcolor', '0x142864');
so.addVariable('screencolor', '0xffffff');
so.addVariable('enablejs', 'true');
so.addVariable('overstretch', 'true');
}
else {
so.addVariable('file', '');
}
if (imageURL.length > 0) {
so.addVariable('image', imageURL);
}
so.write('preview');
</script>
And here's the JavaScript:
try {
var playlistReady = playerReady;
} cat
ch (err) {
//alert('1' + err);
}
playerReady = function(obj) {
setTimeout(function() { checkPlaylistLoaded(obj) }, 1);
try {
playlistReady(obj);
} catch (err) {
//alert(err);
}
}
function itemHandler(obj) {
var item = obj['index'];
var playlist = $("#" + obj['id']).next();
var currentItem = 0;
playlist.children().each(function() {
if (currentItem == item) {
$(this).addClass("playing");
} else {
$(this).removeClass("playing");
}
currentItem++;
});
}
function checkPlaylistLoaded(obj) {
//debugger;
var player = document.getElementById(obj['id']),
jsPlaylist = player.getPlaylist();
if (jsPlaylist.length > 0) {
var playlist = createPlaylist(obj);
populatePlaylist(player, jsPlaylist, playlist);
player.addControllerListener("PLAYLIST", "playlistHandler");
player.addControllerListener("ITEM", "itemHandler");
player.addControllerListener("STOP", "showPlaylist");
player.addModelListener("STATE", "stateListener");
} else {
setTimeout(function() { checkPlaylistLoaded(obj) }, 150);
}
}
function stateListener(obj) {
if (obj.newstate === 'PLAYING') {
hidePlaylist();
}
if (obj.newstate === 'PAUSED') {
showPlaylist();
}
}
function createPlaylist(obj) {
var playerDiv = $("#" + obj['id']);
playerDiv.after("<div class='jw_playlist_playlist'></div>");
return playerDiv.next();
}
function hidePlaylist() {
$('.jw_playlist_playlist').animate({ left: "-320px" }, 1000);
}
function showPlaylist() {
$('.jw_playlist_playlist').animate({ left: "-10px" }, 1000);
}
function playlistHandler(obj) {
var player = document.getElementById(obj['id']),
jsPlaylist = player.getPlaylist(),
playerDiv = $("#" + obj['id']),
playlist = playerDiv.next();
populatePlaylist(player, jsPlaylist, playlist);
}
function populatePlaylist(player, jsPlaylist, playlist) {
playlist.empty();
for (var i = 0; i < jsPlaylist.length; i++) {
var jsItem = jsPlaylist[i];
var alternate = "even";
if (i % 2) {
alternate = "odd";
}
playlist.append("<div id='" + getItemId(jsItem) + "' class='jw_playlist_item " + alternate + "'>" + dump(jsItem) + "</div>");
}
var playlistItem = 0;
playlist.children().each(function() {
var currentItem = playlistItem;
$(this).click(function() {
player.sendEvent("ITEM", currentItem);
});
playlistItem++;
});
}
function getItemId(arr) {
var output = '${link}',
variables = getVars(output),
j;
for (j = 0; j < variables.length; j++) {
var variable = variables[j],
varName = variable.replace('${', '').replace('}', ''),
value = arr[varName];
if (!value) {
value = '';
}
output = output.replace(variable, value);
}
return output;
}
function dump(arr) {
var output = "<div class='jw_playlist_title'>${title}</div><div class='jw_playlist_description'>${description}</div>",
variables = getVars(output),
j;
for (j = 0; j < variables.length; j++) {
var variable = variables[j],
varName = variable.replace('${', '').replace('}', ''),
value = arr[varName];
if (!value) {
value = '';
}
output = output.replace(variable, value);
}
return output;
}
function dumpText(arr) {
var dumped_text = "";
if (typeof (arr) == 'object') {
for (var item in arr) {
var value = arr[item];
if (typeof (value) == 'object') {
dumped_text += "<div class='" + item + "'>";
dumped_text += dump(value);
dumped_text += "</div>";
} else {
dumped_text += "<div class='" + item + "'>" + value + "</div>";
}
}
} else {
dumped_text += arr + " (" + typeof (arr) + ")";
}
return dumped_text;
}
function getVars(str) {
return str.match(/\$\{(.*?)\}/g);
}

Resources