Store Analytics ClientID in Local Variable - vbscript

I'm trying to store the ClientID in a local variable but can't work out how to do this ?
To get the ClientId I have been using :
ga(function (tracker) {
clientId = tracker.get('clientId');
});
But I cannot seem to get this function to do anything useful.
What I am looking to do is get this ClientID into a local variable using VBScript to then store this and append it to various items.
Usually this would be:
strLocalClientID= whateverFunction()
Thanks,
Rick

One way would be to collect all tracker objects (unless you know the trackers name) and use the get method just like in the example
var trackers = ga.getAll();
for (var i=0; i < trackers.length; ++i) {
var tracker = trackers[i];
console.log(tracker.get('clientId'));
}
If you have just one tracker (which will be usually the case) you can simplify this to
var trackers = ga.getAll();
var clientId = trackers[0].get('clientId');

Related

How to make this google script more efficient

I got this script to get into a folder and get the key for each file.
function listFilesInFolder(id) {
var folder = DriveApp.getFolderById('');
var contents = folder.getFiles();
var file;
var name;
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Imported");
var date;
var size;
sheet.clear();
sheet.appendRow(["Name", "Data", "Size", "Id"]);
while(contents.hasNext()) {
file = contents.next();
name = file.getName();
date = file.getDateCreated()
size = file.getSize()
id = file.getId()
data = [name, date, size, id]
sheet.appendRow(data);
//appendRow
}
};
my problem is that taking too much time to finish going through the whole folder, it usually hits run-time limit before it finishes.
The folder contains 1000+ different files, we automatically upload files daily.
is there any way to make this script more efficient?
I believe your goal as follows.
You want to retrieve the file list just under the specific folder using Google Apps Script.
You want to reduce the process cost of your current script in your question.
Modification points:
In your script, appendRow is used in a loop. In this case, the process cost will be high. Ref
And, I thought that in your situation, when Drive API is used, the process cost might be able to be a bit reduced.
When above points are reflected to your script, it becomes as follows.
Modified script:
Before you use this script, please enable Drive API at Advanced Google services.
function listFilesInFolder(id) {
var folderId = "###"; // Please set the folder ID. If you want to use "id" for this, you can use var folderId = id;
// 1. Retrieve file list using Drive API.
var ar = [["Name", "Data", "Size", "Id"]];
var pageToken = "";
do {
const res = Drive.Files.list({corpora: "allDrives", includeTeamDriveItems: true, supportsAllDrives: true, maxResults: 1000, pageToken: pageToken, q: `'${folderId}' in parents`});
ar = ar.concat(res.items.map(({title, createdDate, fileSize, id}) => [title, createdDate, fileSize || 0, id]));
pageToken = res.nextPageToken;
} while(pageToken);
// 2. Put the file list to Spreadsheet.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Imported");
sheet.clear();
sheet.getRange(1, 1, ar.length, ar[0].length).setValues(ar);
}
Note:
From your question, I couldn't understand about the detail of your situation. So in this modified script, the folders in both your Google Drive and the shared Drive can be searched.
References:
Benchmark: Reading and Writing Spreadsheet using Google Apps Script
Files: list

Google AppMaker: Fetch a MAX value

I am not able to fetch a max value from a number field in AppMaker. The field is filled with unique integers from 1 and up. In SQL I would have asked like this:
SET #tKey = (SELECT MAX(ID) FROM GiftCard);
In AppMaker I have done the following (with a bit help from other contributors in this forum) until now, and it returns tKey = "NaN":
var tKey = google.script.run.MaxID();
function MaxID() {
var ID_START_FROM = 11000;
var lock = LockService.getScriptLock();
lock.waitLock(3000);
var query = app.models.GiftCard.newQuery();
query.sorting.ID._descending();
query.limit = 1;
var records = query.run();
var next_id = records.length > 0 ? records[0].ID : ID_START_FROM;
lock.releaseLock();
return next_id;
}
There is also a maxValue() function in AppMaker. However, it seems not to work in that way I use it. If maxvalue() is better to use, please show :-)
It seems that you are looking in direction of auto incremented fields. The right way to achieve it would be using Cloud SQL database. MySQL will give you more flexibility with configuring your ids:
ALTER TABLE GiftCard AUTO_INCREMENT = 11000;
In case you strongly want to stick to Drive Tables you can try to fix your script as follow:
google.script.run
.withSuccessHandler(function(maxId) {
var tKey = maxId;
})
.withFailureHandler(function(error) {
// TODO: handle error
})
.MaxID();
As a side note I would also recommend to set your ID in onBeforeCreate model event as an extra security layer instead of passing it to client and reading back since it can be modified by malicious user.
You can try using Math.max(). Take into consideration the example below:
function getMax() {
var query = app.models.GiftCard.newQuery();
var allRecords = query.run();
allIds = [];
for( var i=0; i<allRecords.length;i++){
allIds.push(allRecords[i].ID);
}
var maxId = Math.max.apply(null, allIds);
return maxId;
}
Hope it helps!
Thank you for examples! The Math.max returned an undefined value. Since this simple case is a "big" issue, I will solve this in another way. This value is meant as a starting value for a sequence only. An SQL base is better yes!

To get value of key from cache using CacheService in google app script

I am trying to implement caching. I've written code in bounded script of spreadsheet. It's working fine i.e. I am able to get values against particular key. But this code is valid only for bounded script.
Does anyone know that how to access value against particular key from separate script?
Code to put in cache:(Bounded Script)
var sp_key = '1231232';
var ss = SpreadsheetApp.openById(sp_Key);
var s = ss.getSheetByName("test_Sheet");
var cache = CacheService.getScriptCache();
var val= "xyz"
cache.put(A, val);
var cache = CacheService.getPublicCache();
Logger.log(cache.get(A));
Above code works fine. But if I want to get the value from unbounded script then what is the best way?
The getScriptCache() method also works in a stand alone Apps Script project.
There is an error in your code. A is not defined. Either put quotes around A or define A as a variable, and assign a value
function scriptCache() {
var sp_key = '1231232';
//var ss = SpreadsheetApp.openById(sp_Key);
//var s = ss.getSheetByName("test_Sheet");
var cache = CacheService.getScriptCache();
var val= "xyz"
cache.put('A', val);
var cache = CacheService.getPublicCache();
Logger.log(cache.get('A'));
}
I ran that code in a stand alone Apps Script and it works.

How to retrieve total view count of large number of pages combined from the GA API

We are interested in the statistics of the different pages combined from the Google Analytics core reporting API. The only way I found to query statistics multiple pages at the same is by creating a filter like so:
ga:pagePath==page?id=a,ga:pagePath==page?id=b,ga:pagePath==page?id=c
And this get escaped inside the filter parameter of the GET query.
However when the GET query gets over 2000 characters I get the following response:
414. That’s an error.
The requested URL /analytics/v3/data/ga... is too large to process. That’s all we know.
Note that just like in the example call the only part that is different per page is a GET parameter in the pagePath, but we have to OR a new filter specifying both the metric (pagePath) as well as the part of the path that is always identical.
Is there any way to specify a large number of different pages to query without hitting this limit in the GET query (I can't find any documentation for doing POST requests)? Or are there alternatives to creating batches of a max of X different pages per query and adding them up on my end?
Instead of using ga:pagePath as part of a filter you should use it as a dimension. You can get up to 10,000 rows per query this way and paginate to get all results. Then parse the results client side to get what you need. Additionally use a filter to scope the results down if possible based on your site structure or page names.
I am sharing a sample code where you can fetch more then 10,000 record data via help of Items PerPage
private void GetDataofPpcInfo(DateTime dtStartDate, DateTime dtEndDate, AnalyticsService gas, List<PpcReportData> lstPpcReportData, string strProfileID)
{
int intStartIndex = 1;
int intIndexCnt = 0;
int intMaxRecords = 10000;
var metrics = "ga:impressions,ga:adClicks,ga:adCost,ga:goalCompletionsAll,ga:CPC,ga:visits";
var r = gas.Data.Ga.Get("ga:" + strProfileID, dtStartDate.ToString("yyyy-MM-dd"), dtEndDate.ToString("yyyy-MM-dd"),
metrics);
r.Dimensions = "ga:campaign,ga:keyword,ga:adGroup,ga:source,ga:isMobile,ga:date";
r.MaxResults = 10000;
r.Filters = "ga:medium==cpc;ga:campaign!=(not set)";
while (true)
{
r.StartIndex = intStartIndex;
var dimensionOneData = r.Fetch();
dimensionOneData.ItemsPerPage = intMaxRecords;
if (dimensionOneData != null && dimensionOneData.Rows != null)
{
var enUS = new CultureInfo("en-US");
intIndexCnt++;
foreach (var lstFirst in dimensionOneData.Rows)
{
var objPPCReportData = new PpcReportData();
objPPCReportData.Campaign = lstFirst[dimensionOneData.ColumnHeaders.IndexOf(dimensionOneData.ColumnHeaders.FirstOrDefault(h => h.Name == "ga:campaign"))];
objPPCReportData.Keywords = lstFirst[dimensionOneData.ColumnHeaders.IndexOf(dimensionOneData.ColumnHeaders.FirstOrDefault(h => h.Name == "ga:keyword"))];
lstPpcReportData.Add(objPPCReportData);
}
intStartIndex = intIndexCnt * intMaxRecords + 1;
}
else break;
}
}
Only one thing is problamatic that your query length shouldn't exceed around 2000 odd characters

Get query string in Google CSE v2

I am using Google CSE v2, and I need to get the query that the user entered. The problem is that it is ajax, and the query is not in the url.
Does anyone know a solution?
Thanks
First off, when you create the search box, you need to give it a 'gname' attribute so you can identify it in your javascript, like so:
<gcse:searchbox gname="storesearch"></gcse:searchbox>
<gcse:searchresults gname="storesearch"></gcse:searchresults>
Or, if you're using the html5 style tags (which you should unless you have a reason not to):
<div class="gcse-searchbox" data-gname="storesearch"></div>
<div class="gcse-searchresults" data-gname="storesearch"></div>
(Replace 'storesearch' with whatever name you want to use to identify this custom search.)
More info on that here: https://developers.google.com/custom-search/docs/element#supported_attributes
Then, you can access the custom search element and get the current query like so:
var cseElement = google.search.cse.element.getElement('storesearch'),
query = cseElement.getInputQuery();
or if you don't need the reference to the element anymore, obviously that could be combined into one line:
var query = google.search.cse.element.getElement('storesearch').getInputQuery();
The docs for that part are here: https://developers.google.com/custom-search/docs/element#cse-element
I know this is already answered correctly. But for those also looking for a simple JS function to achieve this, here you go. Pass it the name of the variable you want to extract from the query string.
var qs = (function(a) {
if (a == "") return {};
var b = {};
for (var i = 0; i < a.length; ++i) {
var p=a[i].split('=');
if (p.length != 2) continue;
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
})(window.location.search.substr(1).split('&'));

Resources