PetaPoco and output parameters from stored procedures? - stored-procedures

I'm trying to setup an output parameter using PetaPoco. I found someone using this sample online:
var ctx = new CustomDBDatabase();
var total = new SqlParameter("Total", System.Data.SqlDbType.Int);
total.Direction = System.Data.ParameterDirection.Output;
var results = ctx.Query<DBEntity>("exec GetDBEntities #StartIndex, #MaxIndex, #TotalCount = #Total out",
id, start, max, total);
int totalCount = (int)total.Value;
However, total.value returns null, even though when I run this statement directly against SQL Server, it returns me 3. Is this setup correctly with PetaPoco? Are output parameters supported?
Thanks.

This is supported. But your current syntax is wrong anyways.
var ctx = new CustomDBDatabase();
var total = new SqlParameter("TotalCount", System.Data.SqlDbType.Int);
total.Direction = System.Data.ParameterDirection.Output;
var results = ctx.Query<DBEntity>("exec GetDBEntities #StartIndex, #MaxIndex, #TotalCount OUTPUT", new { StartIndex = start, MaxIndex = max, TotalCount = total});
int totalCount = (int)total.Value;
Something like this should work though. Not quite sure of the sql syntax but this should get you on your way.

Related

Google Script to Parse/Filter Data and Set Several sub SpreadSheets from master Spreadsheet

I have a master spreadsheet with several drivers and their routes for the day. This needs to be parsed out to several driver sheets. I have one sheet with all the data in the master and another with all the drivers names and spreadsheet ids to run a loop through for all drivers listed. Just runs...no action. Last three comments need to be fixed as well as it errors here and does not like .openById.
function setRoutes(){
var ScheduleSheetURL = "https://docs.google.com/spreadsheets/...";
var ActiveSpreadSheet = SpreadsheetApp.openByUrl(ScheduleSheetURL);
var AllRoutesSheetName = "RoutesIn";
var ActiveSheet = ActiveSpreadSheet.setActiveSheet(ActiveSpreadSheet.getSheetByName(AllRoutesSheetName));
var AllRouteData = ActiveSheet.getRange('A:AZ').getValues();
ActiveSheet = SpreadsheetApp.setActiveSheet(ActiveSpreadSheet.getSheetByName("Drivers"));
//var ActiveDriverCounter = ActiveSheet.getRange("A1:A").getValues();
//var DriverCount = ActiveDriverCounter.filter(String).length;
var DriverCount = ActiveSheet.getLastRow()-1;
var idrvSheetID = "";
var ActiveDriverName = "";
var RouteData = [];
var i = 1;
for (i = 1; i++; i <= DriverCount){
//Get Route Name
ActiveSpreadSheet = SpreadsheetApp.openByUrl(ScheduleSheetURL);
ActiveSheet = ActiveSpreadSheet.setActiveSheet(ActiveSpreadSheet.getSheetByName("Drivers"));
ActiveDriverName = ActiveSheet.getRange(i,1).getValue();
Logger.log(ActiveDriverName);
//Get Drivers Route
ActiveSheet = ActiveSpreadSheet.setActiveSheet(ActiveSpreadSheet.getSheetByName(AllRoutesSheetName));
for (var i = 0; i< AllRouteData.length; i++){
if(AllRouteData[i][1] == ActiveDriverName){
RouteData.push(AllRouteData[i])
Logger.log(RouteData[i]);
}
}
ActiveSpreadSheet = SpreadsheetApp.openByUrl(ScheduleSheetURL);
//Open & Write Driver Sheet
ActiveSheet = SpreadsheetApp.setActiveSheet(ActiveSpreadSheet.getSheetByName("Drivers"));
idrvSheetID = ActiveSheet.getRange(i,2).getValue();
// ActiveSpreadSheet = SpreadsheetApp.openById(idrvSheetID);
// ActiveSheet = ActiveSpreadSheet.setActiveSheet(ActiveSpreadSheet.getSheets()[0]);
// ActiveSheet.getRange(ActiveSheet.getLastRow()+1,1,RouteData.length,RouteData[0].length).setValues(RouteData);
}
}
Issues:
There are several problems with your script:
Every time you want to work on a spreadsheet or sheet, you are using some variant of setActive. I guess you are under the assumption that you need to "activate" a sheet in order to work on it, but that's not true! If you remove all this, your code can be minimized considerably.
You are not defining the outer for loop correctly: for (i = 1; i++; i <= DriverCount){. Second parameter should be the condition, and third one should be what to do at the end of each loop iteration. You have it the other way around.
When trying to filter the routes according to the Driver (if(AllRouteData[i][1] == ActiveDriverName){), you are not specifying the correct array index (arrays are 0-indexed, so 1 here would refer to column B, which doesn't contain the driver's names, so the script won't find any match there.
You are reusing the same loop counter variable (i) in a nested loop (for (var i = 0; i< AllRouteData.length; i++){). This will mess with your outer loop.
Solution:
Considering all these, I've wrote a small script that accomplishes your purpose. I have changed some of the variables names so that they are more meaningful (please check inline comments):
function setRoutes() {
const ScheduleSheetURL = "YOUR-MAIN-SPREADSHEET-URL"; // Change to your spreadsheet URL
const SourceSpreadSheet = SpreadsheetApp.openByUrl(ScheduleSheetURL);
const RoutesSheet = SourceSpreadSheet.getSheetByName("RoutesIn");
const AllRouteData = RoutesSheet.getRange('A:AZ').getValues();
const DriversSheet = SourceSpreadSheet.getSheetByName("Drivers");
const DriverCount = DriversSheet.getLastRow()-1;
const DriversData = DriversSheet.getRange(2, 1, DriverCount, 2).getValues(); // Get all Drivers data
for (let i = 0; i < DriversData.length; i++) { // Loop through all Drivers data
const DriverData = DriversData[i]; // Specific Driver data
const DriverName = DriverData[0]; // Driver name (column A)
const DriverSpreadsheetId = DriverData[1]; // Driver spreadsheet ID (column B)
const DriverRoutes = AllRouteData.filter(routeData => routeData[0] === DriverName); //Filter routes according to driver
const DriverSpreadsheet = SpreadsheetApp.openById(DriverSpreadsheetId); // Get specific Driver spreadsheet
const DriverSheet = DriverSpreadsheet.getSheets()[0]; // Get first sheet in Driver spreadsheet
DriverSheet.getRange(DriverSheet.getLastRow() + 1, 1, DriverRoutes.length, DriverRoutes[0].length)
.setValues(DriverRoutes); // Add routes to driver spreadsheet
}
}

How to find the SearchImpressionShare for a particular keyword?

One could easily find the average position for a keyword using getAveragePositon() method but the same is not available for SearchImpressionShare.
EDIT
I tried to get the SearchImpressionShare by querying the data but that gives me inconsistent data.
function main() {
var keywordId = 297285633818;
var last14dayStatsQuery = "SELECT Id, SearchTopImpressionShare FROM KEYWORDS_PERFORMANCE_REPORT WHERE Id = "+keywordId+" DURING LAST_14_DAYS"
var last14dayReport = AdWordsApp.report(last14dayStatsQuery);
var last14dayRows = last14dayReport.rows();
var last14dayRow = last14dayRows.next();
Logger.log('Keyword: ' + last14dayRow['Id'] + ' SearchTopIS: ' + last14dayRow['SearchTopImpressionShare']);
}
For example, below are the two outputs I received after running the same code twice.
Output 1:
10/16/2019 10:47:29 AM Keyword: 297285633818 SearchTopIS: 0.0
Output 2:
10/16/2019 10:47:45 AM Keyword: 297285633818 SearchTopIS: 0.17
Keywords performance report provides you those data https://developers.google.com/adwords/api/docs/appendix/reports/keywords-performance-report#searchimpressionshare
sample use:
function main () {
var query = "SELECT SearchImpressionShare, Criteria FROM KEYWORDS_PERFORMANCE_REPORT WHERE Clicks > 15 DURING YESTERDAY"
var report = AdWordsApp.report(query)
var rows = report.rows()
while (rows.hasNext()) {
var row = rows.next()
Logger.log('Keyrword %s, Impressions Share %s', row['Criteria'], row['SearchImpressionShare'])
}
}
update:
please note that if you have the same keyword within several ad group you'll get aslo several rows in report, each row for each adgroup. for the whole list of keywords use the following approach:
function main() {
var keywordId = 350608245287;
var last14dayStatsQuery = "SELECT Id, SearchTopImpressionShare FROM KEYWORDS_PERFORMANCE_REPORT WHERE Id = "+keywordId+" DURING LAST_14_DAYS"
var last14dayReport = AdWordsApp.report(last14dayStatsQuery);
var last14dayRows = last14dayReport.rows();
while (last14dayRows.hasNext()) {
var last14dayRow = last14dayRows.next();
Logger.log('Keyword: ' + last14dayRow['Id'] + ' SearchTopIS: ' + last14dayRow['SearchTopImpressionShare']);
}
}
You might find it useful to add ad group parameters to your query such as AdGroupName, AdGroupId.

How to parse Gmail messages to extract data to Google Sheets

I'm working on a R&D project where I collect my server side statistics using Linux commands and output the same to my mail. Now my plan is to read and parse the Gmail content which has my data of the server (as below) and extract it to Google Sheets. My Gmail content looks like below which has data in rows and columns.
Date&Time JVM PID CPU MEM FGC
03-09-2017-09-08-PM abc01_xzy01 12345 1.2% 2.75 3
03-09-2017-09-08-PM abc01_xzy01 12345 3.5% 2.71 4
03-09-2017-09-08-PM abc01_xzy01 12345 4.6% 2.79 5
My idea here is to pull exactly the same way into a Google Sheet. I'm using the below code but it's unable to read the content. I'm thinking if it's related to the RegExp used. Could you please tell me how exactly the code has to be written in the if statement.
function parseEmailMessages(start) {
start = start || 0;
var threads = GmailApp.getInboxThreads(start, 100);
var sheet = SpreadsheetApp.getActiveSheet();
for (var i = 0; i < threads.length; i++) {
var tmp,
message = threads[i].getMessages()[0],
// subject = message.getSubject(),
subject = "SERVER TEST REPORT",
content = message.getPlainBody();
if (content) {
tmp = content.match(/Date&Time:\s*([A-Za-z0-9\s]+)(\r?\n)/);
var username = (tmp && tmp[1]) ? tmp[1].trim() : 'No Date & Time';
tmp = content.match(/JVM:\s*([A-Za-z0-9\s]+)(\r?\n)/);
var username = (tmp && tmp[1]) ? tmp[1].trim() : 'No JVM';
sheet.appendRow([username, email, subject, comment]);
}
}
}
My output just prints No Date & Time and No JVM in the Google Sheets. I want to print the names and data in the columns and rows as given in the mail. Can someone please help me on this and tell me what is the mistake and how to pull the data like expected. Thanks in advance.
If all that is in your email is what you posted above, this will put it in your spreadsheet. Change the email subject and sheet name to suit your needs.
function getGmail() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var threads = GmailApp.search('IMPORTANT1', 0, 10);
for (var i = 0; i < threads.length; i++) {
var messages = GmailApp.getMessagesForThread(threads[i]);
for (var j = 0; j < messages.length; j++) {
var msg=messages[j].getPlainBody();
var msg=msg.trim()
}
}
result1(msg)
}
function result1(range) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = ss.getSheetByName("Sheet1")
var lr=sheet1.getLastRow()
var output=[]
var line=range.split("\n")
for(j=0;j<line.length;j++){
output.push(line[j].split(" "))
}
sheet1.getRange(lr+1, 1, output.length, output[0].length).setValues(output)
}

Google Apps Script

I've created a simple script that reads through an xml file and posts the results to an SQL database. This works perfectly.
I've put a little if statement in the script to identify orders that have already been posted to SQL. Basically if the transactionID in the input array is higher than the highest transactionID on the SQL server it adds the row values to the output array.
It seems that I am missing a trick here because I am getting "TypeError: Cannot call method "getAttribute" of undefined. (line 18, file "Code")" when trying to compare the current xml row to the last transaction ID.
I've done some searching and whilst I can see people with similar problems the explanations don't make a whole lot of sense to me.
Anyway, here is the relevant part of the code. Note that this all works perfectly without the if() bit.
function getXML() {
var id = lastTransactionID();
var xmlSite = UrlFetchApp.fetch("https://api.eveonline.com/corp/WalletTransactions.xml.aspx?KeyID=1111&vCode=1111&accountKey=1001").getContentText();
var xmlDoc = XmlService.parse(xmlSite);
var root = xmlDoc.getRootElement();
var row = new Array();
row = root.getChild("result").getChild("rowset").getChildren("row");
var output = new Array();
var i = 0;
for (j=0;i<row.length;j++){
if(row[j].getAttribute("transactionID").getValue()>id){ //Produces: TypeError: Cannot call method "getAttribute" of undefined. (line 18, file "Code")
output[i] = new Array();
output[i][0] = row[j].getAttribute("transactionDateTime").getValue();
output[i][1] = row[j].getAttribute("transactionID").getValue();
output[i][2] = row[j].getAttribute("quantity").getValue();
output[i][3] = row[j].getAttribute("typeName").getValue();
output[i][4] = row[j].getAttribute("typeID").getValue();
output[i][5] = row[j].getAttribute("price").getValue();
output[i][6] = row[j].getAttribute("clientID").getValue();
output[i][7] = row[j].getAttribute("clientName").getValue();
output[i][8] = row[j].getAttribute("stationID").getValue();
output[i][9] = row[j].getAttribute("stationName").getValue();
output[i][10] = row[j].getAttribute("transactionType").getValue();
output[i][11] = row[j].getAttribute("transactionFor").getValue();
output[i][12] = row[j].getAttribute("journalTransactionID").getValue();
output[i][13] = row[j].getAttribute("clientTypeID").getValue();
i++;
}
}
insert(output,output.length);
}
I have seen my mistake and corrected.
Mistake was in the for loop.
for (j=0;i

Node.js url.parse result back to string

I am trying to do some simple pagination.
To that end, I'm trying to parse the current URL, then produce links to the same query, but with incremented and decremented page parameters.
I've tried doing the following, but it produces the same link, without the new page parameter.
var parts = url.parse(req.url, true);
parts.query['page'] = 25;
console.log("Link: ", url.format(parts));
The documentation for the URL module seems to suggest that format is what I need but I'm doing something wrong.
I know I could iterate and build up the string manually, but I was hoping there's an existing method for this.
If you look at the latest documentation, you can see that url.format behaves in the following way:
search will be used in place of query
query (object; see querystring) will only be used if search is absent.
And when you modify query, search remains unchanged and it uses it. So to force it to use query, simply remove search from the object:
var url = require("url");
var parts = url.parse("http://test.com?page=25&foo=bar", true);
parts.query.page++;
delete parts.search;
console.log(url.format(parts)); //http://test.com/?page=26&foo=bar
Make sure you're always reading the latest version of the documentation, this will save you a lot of trouble.
Seems to me like it's a bug in node. You might try
// in requires
var url = require('url');
var qs = require('querystring');
// later
var parts = url.parse(req.url, true);
parts.query['page'] = 25;
parts.query = qs.stringify(parts.query);
console.log("Link: ", url.format(parts));
The other answer is good, but you could also do something like this. The querystring module is used to work with query strings.
var querystring = require('querystring');
var qs = querystring.parse(parts.query);
qs.page = 25;
parts.search = '?' + querystring.stringify(qs);
var newUrl = url.format(parts);
To dry out code and get at URL variables without needing to require('url') I used:
/*
Used the url module to parse and place the parameters into req.urlparams.
Follows the same pattern used for swagger API path variables that load
into the req.params scope.
*/
app.use(function(req, res, next) {
var url = require('url');
var queryURL = url.parse(req.url, true);
req.urlparams = queryURL.query;
next();
});
var myID = req.urlparams.myID;
This will parse and move the url variables into the req.urlparams variable. It runs early in the request workflow so is available for all expressjs paths.

Resources