Modify a SendGoogleForm script v3 - google-apps-script

I have almost got all the way now with my script but now I got stuck on an error telling me "66: Missing semicolon". I have tried with what I can, but I do not understand.
I read about this and the semicolon should be used after a function is assigned to a variable if I understand correct, but the powershell code I put inside the "" should not be affected, right? Maybe I got this all wrong.
/* Send Google Form by Email v2.1 */
/* For customization, contact the developer at amit#labnol.org */
/* Tutorial: http://www.labnol.org/?p=20884 */
function Initialize() {
var triggers = ScriptApp.getProjectTriggers();
for(var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
ScriptApp.newTrigger("SendGoogleForm")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onFormSubmit()
.create();
}
function SendGoogleForm(e)
{
try
{
//Här fyller du i mailadresserna för resp avdelning.
var it = "";
//Ärende på mailet
var subject = "Ny/redigerad anställning";
// Variables
var test = "Test";
var temporarypass = "Provide a Temporary Password for this user";
var semicolon = ";";
//Slår ihop alla mailadresser till en.
var email = it;
// You may replace this with another email address
//var email = Session.getActiveUser().getEmail();
var s = SpreadsheetApp.getActiveSheet();
var columns = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];
var message = "";
// Only include form fields that are not blank
for ( var keys in columns ) {
var key = columns[keys];
if ( e.namedValues[key] && (e.namedValues[key] != "") ) {
message += key + ' :: '+ e.namedValues[key] + "<br><br>";
}
if (key == "Förnamn")
var fornamn = e.namedValues[key];
else if (key == "Efternamn")
var efternamn = e.namedValues[key];
else if (key == "Placering")
var placering = e.namedValues[key];
else if (key == "Titel")
var titel = e.namedValues[key];
else if (key == "Avdelning")
var avdelning = e.namedValues[key];
}
//Output for the email that is sent.
subject += ", " + fornamn + " " + efternamn ;
message +="function Remove-DiacriticsAndSpaces { Param( [String]$inputString ) $sb = [Text.Encoding]::ASCII.GetString([Text.Encoding]::GetEncoding("Cyrillic").GetBytes($inputString)); return($sb -replace '[^a-zA-Z0-9]', '')}; New-ADUser -SamAccountName (((Remove-DiacriticsAndSpaces -InputString '"+fornamn+"')+"."+(Remove-DiacriticsAndSpaces -InputString '"+efternamn+"')).ToLower()) -UserPrincipalName (((Remove-DiacriticsAndSpaces -InputString '"+fornamn+"')+"."+(Remove-DiacriticsAndSpaces -InputString '"+efternamn"')+"#test.com").ToLower()) -EmailAddress (((Remove-DiacriticsAndSpaces -InputString '"+fornamn+"')+"."+(Remove-DiacriticsAndSpaces -InputString '"+efternamn+"')+"#test.com").ToLower()) -Name '"+fornamn+" "+efternamn+"' -GivenName '"+fornamn+"' -Surname '"+efternamn+"' -Description '"+test+", "+avdelning+", "+titel+"' -Title '"+titel+"' -OfficePhone ' ' -Path 'OU=Users,OU=test,DC=intern,DC=test,DC=se' -Company 'test' -Department '"+avdelning+"' -Title '"+titel+"'; $NewPassword = (Read-Host -Prompt 'Provide a Temporary Password for this user' -AsSecureString); Set-ADAccountPassword -Identity '"+fornamn+"."+efternamn+"' -NewPassword $NewPassword -Reset; Set-ADAccountControl -Identity '"+fornamn+"."+efternamn+"' -Enabled $true";
var htmlBody = "<html><p>" + message + "</p></html>";
MailApp.sendEmail(email, subject, message, {'htmlBody': htmlBody });
} catch (e) {
Logger.log(e.toString());
}
}
Thank you!

This is a very dense thing to follow up as this string is endless and full of brackets, but here is my try:
Change the brackets from the word "Cyrillic" to 'Cyrillic'
There are several "stop points" without + (only when they are next to "+fornamn+"')+ closing with pharentesis, the others are fine):
fornamn+"')+"."+(Re
should be
fornamn+"')+"+"."+"+(Re
Change the brackets from "#test.com" to '#test.com' or +"#test.com"+
There is a missing + for one "efternamn": '"+efternamn"' to '"+efternamn+"')
After these changes it didn't show any other error, but I can't tell if the injected code would work.
To save you some time, here is the full string with my corrections:
"function Remove-DiacriticsAndSpaces { Param( [String]$inputString ) $sb = [Text.Encoding]::ASCII.GetString([Text.Encoding]::GetEncoding('Cyrillic').GetBytes($inputString)); return($sb -replace '[^a-zA-Z0-9]', '')}; New-ADUser -SamAccountName (((Remove-DiacriticsAndSpaces -InputString '"+fornamn+"')+"+"."+"+(Remove-DiacriticsAndSpaces -InputString '"+efternamn+"')).ToLower()) -UserPrincipalName (((Remove-DiacriticsAndSpaces -InputString '"+fornamn+"')+"+"."+"+(Remove-DiacriticsAndSpaces -InputString '"+efternamn+"')+'#test.com').ToLower()) -EmailAddress (((Remove-DiacriticsAndSpaces -InputString '"+fornamn+"')+"+"."+"+(Remove-DiacriticsAndSpaces -InputString '"+efternamn+"')+'#test.com').ToLower()) -Name '"+fornamn+" "+efternamn+"' -GivenName '"+fornamn+"' -Surname '"+efternamn+"' -Description '"+test+", "+avdelning+", "+titel+"' -Title '"+titel+"' -OfficePhone ' ' -Path 'OU=Users,OU=test,DC=intern,DC=test,DC=se' -Company 'test' -Department '"+avdelning+"' -Title '"+titel+"'; $NewPassword = (Read-Host -Prompt 'Provide a Temporary Password for this user' -AsSecureString); Set-ADAccountPassword -Identity '"+fornamn+"."+efternamn+"' -NewPassword $NewPassword -Reset; Set-ADAccountControl -Identity '"+fornamn+"."+efternamn+"' -Enabled $true"; ```

Related

Twitter Media Upload OAuth1.0a auth error

I am trying to implement twitter media upload on google apps script via OAuth1.0a... as there has been no oauth2 for media uploads since 2 years. Following is the code. Still facing 401, 402, 403 , 400... all such return codes since last one week. Is this end point not working? anyone has any info? any ideas why its failing again and again.
using OAuth1 (https://github.com/googleworkspace/apps-script-oauth1/tree/3f3a6697d95a3ed9a91d09c65ffc34941136f587)
var url = 'https://upload.twitter.com/1.1/media/upload.json?media_category=tweet_image';
var baseUrl = 'https://upload.twitter.com/1.1/media/upload.json';
var params = {
'payload': {'media': imageBlob},
'method': 'POST',
'muteHttpExceptions' : true
};
var token = JSON.parse(PropertiesService.getUserProperties().getProperty("oauth1."+ account));
var oauth_token = token.oauth_token
var oauth_token_secret = token.oauth_token_secret
var oauth_consumer_key = PropertiesService.getUserProperties().getProperty("TWITTER_CONSUMER_KEY");
var oauth_consumer_secret = PropertiesService.getUserProperties().getProperty("TWITTER_CONSUMER_SECRET");
const method = params['method'] || 'post';
params['method'] = method;
const oauthParameters = {
oauth_version: "1.0",
oauth_token: oauth_token,
oauth_consumer_key: oauth_consumer_key,
oauth_signature_method: "HMAC-SHA1",
oauth_timestamp: (Math.floor((new Date()).getTime() / 1000)).toString(),
};
oauthParameters.oauth_nonce = oauthParameters.oauth_timestamp + Math.floor(Math.random() * 100000000);
const payload = params['payload'] || {};
const q = {"media_category": "tweet_image"} //parms from url
const queryKeys = Object.keys(oauthParameters).concat(Object.keys(payload)).concat(Object.keys(q)).sort();
const baseString = queryKeys.reduce(function(acc, key, idx) {
if (idx) acc += encodeURIComponent("&");
if (oauthParameters.hasOwnProperty(key))
acc += _encode(key + "=" + oauthParameters[key]);
else if (payload.hasOwnProperty(key))
acc += _encode(key + "=" + _encode(payload[key]));
return acc;
}, method.toUpperCase() + '&' + _encode(baseUrl) + '&');
oauthParameters.oauth_signature = Utilities.base64Encode(
Utilities.computeHmacSignature(
Utilities.MacAlgorithm.HMAC_SHA_1,
baseString, oauth_consumer_secret + '&' + oauth_token_secret
)
);
if (!params['headers']) params['headers'] = {};
params['headers']['authorization'] = "OAuth " + Object.keys(oauthParameters)
.sort().reduce(function(acc, key) {
acc.push(key + '="' + _encode(oauthParameters[key]) + '"');
return acc;
}, []).join(', ');
params['payload'] = Object.keys(payload).reduce(function(acc, key) {
acc.push(key + '=' + _encode(payload[key]));
return acc;
}, []).join('&');
console.log(params)
response = UrlFetchApp.fetch(url, params);
for info...other than this, I also tried this repo - https://github.com/airhadoken/twitter-lib
still facing similar issues.
EDIT: on postman it works.. somethings wrong with the code then.. :(

Google Apps Script: Saving Gmail Attachment to Google Drive and replacement of characters in the saved attachment file name

how can I swap characters from the filename that is saved in GDrive? e.g. "/" to "-"
I am using this great script -> https://github.com/ahochsteger/gmail2gdrive/blob/master/Code.gs &
https://github.com/ahochsteger/gmail2gdrive/blob/master/Config.gs
It works really well.
But i would like to exchange letters for the attachment filename that is saved.
I use this script from https://github.com/ahochsteger/gmail2gdrive:
Code.gs
// Gmail2GDrive
// https://github.com/ahochsteger/gmail2gdrive
/**
* Returns the label with the given name or creates it if not existing.
*/
function getOrCreateLabel(labelName) {
var label = GmailApp.getUserLabelByName(labelName);
if (label == null) {
label = GmailApp.createLabel(labelName);
}
return label;
}
/**
* Recursive function to create and return a complete folder path.
*/
function getOrCreateSubFolder(baseFolder,folderArray) {
if (folderArray.length == 0) {
return baseFolder;
}
var nextFolderName = folderArray.shift();
var nextFolder = null;
var folders = baseFolder.getFolders();
while (folders.hasNext()) {
var folder = folders.next();
if (folder.getName() == nextFolderName) {
nextFolder = folder;
break;
}
}
if (nextFolder == null) {
// Folder does not exist - create it.
nextFolder = baseFolder.createFolder(nextFolderName);
}
return getOrCreateSubFolder(nextFolder,folderArray);
}
/**
* Returns the GDrive folder with the given path.
*/
function getFolderByPath(path) {
var parts = path.split("/");
if (parts[0] == '') parts.shift(); // Did path start at root, '/'?
var folder = DriveApp.getRootFolder();
for (var i = 0; i < parts.length; i++) {
var result = folder.getFoldersByName(parts[i]);
if (result.hasNext()) {
folder = result.next();
} else {
throw new Error( "folder not found." );
}
}
return folder;
}
/**
* Returns the GDrive folder with the given name or creates it if not existing.
*/
function getOrCreateFolder(folderName) {
var folder;
try {
folder = getFolderByPath(folderName);
} catch(e) {
var folderArray = folderName.split("/");
folder = getOrCreateSubFolder(DriveApp.getRootFolder(), folderArray);
}
return folder;
}
/**
* Processes a message
*/
function processMessage(message, rule, config) {
Logger.log("INFO: Processing message: "+message.getSubject() + " (" + message.getId() + ")");
var messageDate = message.getDate();
var attachments = message.getAttachments();
for (var attIdx=0; attIdx<attachments.length; attIdx++) {
var attachment = attachments[attIdx];
Logger.log("INFO: Processing attachment: "+attachment.getName());
var match = true;
if (rule.filenameFromRegexp) {
var re = new RegExp(rule.filenameFromRegexp);
match = (attachment.getName()).match(re);
}
if (!match) {
Logger.log("INFO: Rejecting file '" + attachment.getName() + " not matching" + rule.filenameFromRegexp);
continue;
}
try {
var folder = getOrCreateFolder(Utilities.formatDate(messageDate, config.timezone, rule.folder));
var file = folder.createFile(attachment);
var filename = file.getName();
if (rule.filenameFrom && rule.filenameTo && rule.filenameFrom == file.getName()) {
filename = Utilities.formatDate(messageDate, config.timezone, rule.filenameTo.replace('%s',message.getSubject()));
Logger.log("INFO: Renaming matched file '" + file.getName() + "' -> '" + filename + "'");
file.setName(filename);
}
else if (rule.filenameTo) {
filename = Utilities.formatDate(messageDate, config.timezone, rule.filenameTo.replace('%s',message.getSubject()));
Logger.log("INFO: Renaming '" + file.getName() + "' -> '" + filename + "'");
file.setName(filename);
}
file.setDescription("Mail title: " + message.getSubject() + "\nMail date: " + message.getDate() + "\nMail link: https://mail.google.com/mail/u/0/#inbox/" + message.getId());
Utilities.sleep(config.sleepTime);
} catch (e) {
Logger.log(e);
}
}
}
/**
* Generate HTML code for one message of a thread.
*/
function processThreadToHtml(thread) {
Logger.log("INFO: Generating HTML code of thread '" + thread.getFirstMessageSubject() + "'");
var messages = thread.getMessages();
var html = "";
for (var msgIdx=0; msgIdx<messages.length; msgIdx++) {
var message = messages[msgIdx];
html += "From: " + message.getFrom() + "<br />\n";
html += "To: " + message.getTo() + "<br />\n";
html += "Date: " + message.getDate() + "<br />\n";
html += "Subject: " + message.getSubject() + "<br />\n";
html += "<hr />\n";
html += message.getBody() + "\n";
html += "<hr />\n";
}
return html;
}
/**
* Generate a PDF document for the whole thread using HTML from .
*/
function processThreadToPdf(thread, rule) {
Logger.log("INFO: Saving PDF copy of thread '" + thread.getFirstMessageSubject() + "'");
var folder = getOrCreateFolder(rule.folder);
var html = processThreadToHtml(thread);
var blob = Utilities.newBlob(html, 'text/html');
var pdf = folder.createFile(blob.getAs('application/pdf')).setName(thread.getFirstMessageSubject() + ".pdf");
return pdf;
}
/**
* Main function that processes Gmail attachments and stores them in Google Drive.
* Use this as trigger function for periodic execution.
*/
function Gmail2GDrive() {
if (!GmailApp) return; // Skip script execution if GMail is currently not available (yes this happens from time to time and triggers spam emails!)
var config = getGmail2GDriveConfig();
var label = getOrCreateLabel(config.processedLabel);
var end, start, runTime;
start = new Date(); // Start timer
Logger.log("INFO: Starting mail attachment processing.");
if (config.globalFilter===undefined) {
config.globalFilter = "has:attachment -in:trash -in:drafts -in:spam";
}
// Iterate over all rules:
for (var ruleIdx=0; ruleIdx<config.rules.length; ruleIdx++) {
var rule = config.rules[ruleIdx];
var gSearchExp = config.globalFilter + " " + rule.filter + " -label:" + config.processedLabel;
if (config.newerThan != "") {
gSearchExp += " newer_than:" + config.newerThan;
}
var doArchive = rule.archive == true;
var doPDF = rule.saveThreadPDF == true;
// Process all threads matching the search expression:
var threads = GmailApp.search(gSearchExp);
Logger.log("INFO: Processing rule: "+gSearchExp);
for (var threadIdx=0; threadIdx<threads.length; threadIdx++) {
var thread = threads[threadIdx];
end = new Date();
runTime = (end.getTime() - start.getTime())/1000;
Logger.log("INFO: Processing thread: "+thread.getFirstMessageSubject() + " (runtime: " + runTime + "s/" + config.maxRuntime + "s)");
if (runTime >= config.maxRuntime) {
Logger.log("WARNING: Self terminating script after " + runTime + "s");
return;
}
// Process all messages of a thread:
var messages = thread.getMessages();
for (var msgIdx=0; msgIdx<messages.length; msgIdx++) {
var message = messages[msgIdx];
processMessage(message, rule, config);
}
if (doPDF) { // Generate a PDF document of a thread:
processThreadToPdf(thread, rule);
}
// Mark a thread as processed:
thread.addLabel(label);
if (doArchive) { // Archive a thread if required
Logger.log("INFO: Archiving thread '" + thread.getFirstMessageSubject() + "' ...");
thread.moveToArchive();
}
}
}
end = new Date(); // Stop timer
runTime = (end.getTime() - start.getTime())/1000;
Logger.log("INFO: Finished mail attachment processing after " + runTime + "s");
}
and for Config.gs:
/**
* Configuration for Gmail2GDrive
* See https://github.com/ahochsteger/gmail2gdrive/blob/master/README.md for a config reference
*/
function getGmail2GDriveConfig() {
return {
// Global filter
"globalFilter": "-in:trash -in:drafts -in:spam",
// Gmail label for processed threads (will be created, if not existing):
"processedLabel": "to-gdrive/processed",
// Sleep time in milli seconds between processed messages:
"sleepTime": 100,
// Maximum script runtime in seconds (google scripts will be killed after 5 minutes):
"maxRuntime": 280,
// Only process message newer than (leave empty for no restriction; use d, m and y for day, month and year):
"newerThan": "1m",
// Timezone for date/time operations:
"timezone": "GMT",
// Processing rules:
"rules": [
{ // Store all attachments sent to my.name+scans#gmail.com to the folder "Scans"
"filter": "has:attachment to:my.name+scans#gmail.com",
"folder": "'Scans'-yyyy-MM-dd"
},
{ // Store all attachments from example1#example.com to the folder "Examples/example1"
"filter": "has:attachment from:example1#example.com",
"folder": "'Examples/example1'"
},
{ // Store all pdf attachments from example2#example.com to the folder "Examples/example2"
"filter": "has:attachment from:example2#example.com",
"folder": "'Examples/example2'",
"filenameFromRegexp": ".*\.pdf$"
},
{ // Store all attachments from example3a#example.com OR from:example3b#example.com
// to the folder "Examples/example3ab" while renaming all attachments to the pattern
// defined in 'filenameTo' and archive the thread.
"filter": "has:attachment (from:example3a#example.com OR from:example3b#example.com)",
"folder": "'Examples/example3ab'",
"filenameTo": "'file-'yyyy-MM-dd-'%s.txt'",
"archive": true
},
{
// Store threads marked with label "PDF" in the folder "PDF Emails" als PDF document.
"filter": "label:PDF",
"saveThreadPDF": true,
"folder": "PDF Emails"
},
{ // Store all attachments named "file.txt" from example4#example.com to the
// folder "Examples/example4" and rename the attachment to the pattern
// defined in 'filenameTo' and archive the thread.
"filter": "has:attachment from:example4#example.com",
"folder": "'Examples/example4'",
"filenameFrom": "file.txt",
"filenameTo": "'file-'yyyy-MM-dd-'%s.txt'"
}
]
};
}
I use this part to save the PDF attachments
{ // Store all pdf attachments from example2#example.com to the folder "Examples/example2"
"filter": "has:attachment from:example2#example.com",
"folder": "'Examples/example2'",
"filenameFromRegexp": ".*\.pdf$"
},
However, the character "/" is often used in the filename of the attachment. e.g. "Konto/postbox3226.pdf"
How can I replace this with e.g. "-" to "Konto-postbox3226.pdf"
Does that work with the replace command? If so, how do I have to use this?
many thanks for your help
Okay, I have taken a deeper look at the code and I found how to change the name of the file that it is stored in Google Drive.
In code.gs line 92:
try {
var folder = getOrCreateFolder(Utilities.formatDate(messageDate, config.timezone, rule.folder));
// NEW CODE
var new_filename = attachment.getName()
new_filename = new_filename.replace('/','-')
attachment.setName(new_filename)
var file = folder.createFile(attachment);
Reference
File.getName()
File.setName(name)
Folder.createFile(blob)
Let me know if that finally works

Powershell - JSON format to PAC file convert

I have used the following code to display JSON results but now need to change the script to display the output instead of side by side. I have tried a script like below, but just cant seem to get it to do what I want.
My question is :
I want to remove || before the last bracket. if (shExpMatch(host, "*.lync.com") || shExpMatch(host, "*.teams.microsoft.com") || shExpMatch(host, "teams.microsoft.com") || ) As a result , it will be if (shExpMatch(host, "*.lync.com") || shExpMatch(host, "*.teams.microsoft.com") || shExpMatch(host, "teams.microsoft.com"))
I need to change the script to display the my desired output instead of side by side.
Here is my script :
$result = Invoke-WebRequest "https://endpoints.office.com/endpoints/worldwide?noipv6&ClientRequestId=b10c5ed1-bad1-445f-b386-b919946339a7"
$services = ConvertFrom-Json $result
$likeFilter = "12"
$services = $services | Where-Object { $_.id -like $likeFilter }
$urls = [System.Collections.ArrayList]#()
$services
function add_url($url){
if(!$urls.Contains($url)){ $urls.Add($url); }
}
foreach($service in $services){
foreach($url in $service.urls){ add_url($url);
}
}
# OUTPUT
$txt_proxypacText += "// This PAC file will provide proxy config to Microsoft 365 services`r`n"
$txt_proxypacText += "// using data from the public web service for all endpoints`r`n"
$txt_proxypacText += "function FindProxyForURL(url, host)`r`n"
$txt_proxypacText += "{`r`n"
$txt_proxypacText += "var direct = ""DIRECT"";`r`n"
$txt_proxypacText += "var proxyServer = ""PROXY 10.11.12.13:8080"";`r`n"
$txt_proxypacText += "host = host.toLowerCase();`r`n"
$txt_proxypacText += "if ("
foreach($url in $urls){
$txt_proxypacText += "shExpMatch(host, ""$url"") || "
}
$txt_proxypacText += ")`r`n"
$txt_proxypacText += "{`r`n"
$txt_proxypacText += "`r`n return direct;"
$txt_proxypacText += "`r`n}"
$txt_proxypacText += "`r`n return proxyServer;"
$txt_proxypacText += "`r`n}"
Output:
// This PAC file will provide proxy config to Microsoft 365 services
// using data from the public web service for all endpoints
function FindProxyForURL(url, host)
{
var direct = "DIRECT";
var proxyServer = "PROXY 10.11.12.13:8080";
host = host.toLowerCase();
if (shExpMatch(host, "*.lync.com") || shExpMatch(host, "*.teams.microsoft.com") || shExpMatch(host, "teams.microsoft.com") || )
{
return direct;
}
return proxyServer;
}
My Desired Output :
// This PAC file will provide proxy config to Microsoft 365 services
// using data from the public web service for all endpoints
function FindProxyForURL(url, host)
{
var direct = "DIRECT";
var proxyServer = "PROXY 10.11.12.13:8080";
host = host.toLowerCase();
if(shExpMatch(host, "*.lync.com")
|| shExpMatch(host, "*.teams.microsoft.com")
|| shExpMatch(host, "teams.microsoft.com"))
{
return direct;
}
return proxyServer;
}
I would make use of a Here-String with a preformated set of shExpMatch(..) lines.
Using that also relieves you from doubling quotes and string concatenations using +=
# demo urls
$urls = "*.lync.com", "*.teams.microsoft.com", "teams.microsoft.com"
$hostMatches = $(for ($i = 0; $i -lt $urls.Count; $i++) {
$prefix = if ($i -eq 0) { '' } else { ' || '}
'{0}shExpMatch(host, "{1}")'-f $prefix, $urls[$i]
}) -join [Environment]::NewLine
$txt_proxypacText = #"
// This PAC file will provide proxy config to Microsoft 365 services
// using data from the public web service for all endpoints
function FindProxyForURL(url, host)
{
var direct = "DIRECT";
var proxyServer = "PROXY 10.11.12.13:8080";
host = host.toLowerCase();
if ($hostMatches)
{
return direct;
}
return proxyServer;
}
"#
$txt_proxypacText
Output:
// This PAC file will provide proxy config to Microsoft 365 services
// using data from the public web service for all endpoints
function FindProxyForURL(url, host)
{
var direct = "DIRECT";
var proxyServer = "PROXY 10.11.12.13:8080";
host = host.toLowerCase();
if (shExpMatch(host, "*.lync.com")
|| shExpMatch(host, "*.teams.microsoft.com")
|| shExpMatch(host, "teams.microsoft.com"))
{
return direct;
}
return proxyServer;
}
As requested, I think the top part of the code, where you are gathering the urls in an arraylist can be done much easier.
One note before: You are using a $likeFilter variable with a string "12".
In that case, you could probably better use the -eq operator instead of the -like operator that has more use for filtering with wildcards (i.e. "12*").
For now, I'm assuming you want to get only the service with id matching "12" exactly.
$url = "https://endpoints.office.com/endpoints/worldwide?noipv6&ClientRequestId=b10c5ed1-bad1-445f-b386-b919946339a7"
$filter = 12
# get an array of urls from the service(s) that get through the filter
$urls = ((Invoke-WebRequest $url | ConvertFrom-Json) | Where-Object { $_.id -eq $filter }).urls | Select-Object -Unique
# EXAMPLE prepare begin
$urls = #(
'microsoft.com',
'*.microsoft.com',
'teams.microsoft.com',
'*.teams.microsoft.com')
# EXAMPLE prepare End
$urlLines = $urls |
ForEach-Object { return $_.Trim() } |
ForEach-Object {
if($_.StartsWith('*.')) {
return "shExpMatch(host, '$($_)')"
} else {
return "host == '$($_)'"
}}
$innerIf = [String]::Join("`r`n" + (' ' * 8) + "|| ", $urlLines)
#// $txt_proxypacText += " if ($($innerIf))"
Write-Host " if ($($innerIf))"
# Output:
# if (host == "microsoft.com"
# || shExpMatch(host, "*.microsoft.com")
# || host == "teams.microsoft.com"
# || shExpMatch(host, "*.teams.microsoft.com"))
I got this - simple counter method:
$counter = 0
foreach($url in $urls){
If ($counter -eq $urls.Count){
$txt_proxypacText += "shExpMatch(host, ""$url"") `r`n"
}else{
$txt_proxypacText += "shExpMatch(host, ""$url"") || `r`n"
}
$counter++
}
Probably needs some tidying up with the tab characters.

SQLite Database on Host Server

I'm trying to build a web page with a SQLite database. Everything works except the tables are being stored on the local machine, not the host server. So each user sees only the data they entered, which is pretty useless! How do I point SQLite to the server?
I assume the chages would be made here;
var createStatement = "CREATE TABLE IF NOT EXISTS Contacts (id INTEGER PRIMARY KEY AUTOINCREMENT, firstName TEXT, lastName TEXT, phone TEXT)";
var selectAllStatement = "SELECT * FROM Contacts";
var insertStatement = "INSERT INTO Contacts (firstName, lastName, phone) VALUES (?, ?, ?)";
var updateStatement = "UPDATE Contacts SET firstName = ?, lastName = ?, phone = ? WHERE id = ?";
var deleteStatement = "DELETE FROM Contacts WHERE id=?";
var dropStatement = "DROP TABLE Contacts";
But all the code is listed below...............
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Best Test</title>
</head>
<body>
<?php
ini_set ("display_errors", "1");
error_reporting(E_ALL);
$uploads_dir = 'uploads';
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],"uploads/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"]."<br>";
$fname = $_FILES["file"]["name"];
echo "fname = " . $fname;
}
}
}
else
{
echo "Invalid file";
}
?>
<div align="center">
<input type="hidden" id="id"/>
First name:<input type="text" id="firstName"/><br/>
Last name:<input type="text" id="lastName"/><br/>
<button onClick="resetForm()">Reset Form</button>
<button onClick="updateRecord()">Update </button>
<button onClick="preset()">Insert & Procede to Picture Selection</button>
<button onClick="insertRecord()">Insert</button>
<button onClick="dropTable()">Drop Table</button>
<div id="results"></div>
</div>
</body>
<script>
var results = document.getElementById('results');
var id = document.getElementById('id');
var firstName = document.getElementById('firstName');
var lastName = document.getElementById('lastName');
var phone = 6;
var createStatement = "CREATE TABLE IF NOT EXISTS Contacts (id INTEGER PRIMARY KEY AUTOINCREMENT, firstName TEXT, lastName TEXT, phone TEXT)";
var selectAllStatement = "SELECT * FROM Contacts";
var insertStatement = "INSERT INTO Contacts (firstName, lastName, phone) VALUES (?, ?, ?)";
var updateStatement = "UPDATE Contacts SET firstName = ?, lastName = ?, phone = ? WHERE id = ?";
var deleteStatement = "DELETE FROM Contacts WHERE id=?";
var dropStatement = "DROP TABLE Contacts";
var db = openDatabase("AddressBook", "1.0", "Address Book", 200000);
var dataset;
createTable();
function onError(tx, error) {
alert(error.message);
}
function showRecords() {
results.innerHTML = '';
db.transaction(function(tx) {
tx.executeSql(selectAllStatement, [], function(tx, result) {
dataset = result.rows;
for (var i = 0, item = null; i < dataset.length; i++) {
item = dataset.item(i);
results.innerHTML +=
'<li>' + item['lastName'] + ' , ' + item['firstName'] + ' , ' + item['phone'] +' edit ' +
'delete</li>';
}
});
});
}
function createTable() {
db.transaction(function(tx) {
tx.executeSql(createStatement, [], showRecords, onError);
});
}
function insertRecord() {
db.transaction(function(tx) {
tx.executeSql(insertStatement, [firstName.value, lastName.value, phone.value], loadAndReset, onError);
});
}
function preset(){
what ="/uploads/" + "<?php echo $fname; ?>";
alert("what = " + what);
insertRecord2();
}
function insertRecord2() {
alert("Function 2 Started");
db.transaction(function(tx) {
tx.executeSql(insertStatement, [firstName.value, lastName.value, what], loadAndReset, onError);
alert("Function 2 Finished");
});
}
function loadRecord(i) {
var item = dataset.item(i);
firstName.value = item['firstName'];
lastName.value = item['lastName'];
phone.value = item['phone'];
id.value = item['id'];
}
function updateRecord() {
db.transaction(function(tx) {
tx.executeSql(updateStatement, [firstName.value, lastName.value, phone.value, id.value], loadAndReset, onError);
});
}
function updateRecord2() {
db.transaction(function(tx) {
tx.executeSql(updateStatement, [firstName.value, lastName.value, phone.value, id.value], loadAndReset, onError);
});
fnPass();
}
function deleteRecord(id) {
db.transaction(function(tx) {
tx.executeSql(deleteStatement, [id], showRecords, onError);
});
resetForm();
}
function dropTable() {
db.transaction(function(tx) {
tx.executeSql(dropStatement, [], showRecords, onError);
});
resetForm();
}
function loadAndReset(){
resetForm();
showRecords();
}
function resetForm(){
firstName.value = '';
lastName.value = '';
phone.value = '';
id.value = '';
}
</script>
</body>
Text to Pass: <input type='text' id='idTextToPass'/><br/>
<input type='button' value='Pass' onclick='fnPass();'/>
</html>
Thanks
Don
You're not actually using SQLite directly; you are using HTML5 LocalStorage, whose backing store is browser-dependent. If you want to use a server-side database, then your database interaction needs to happen on the server side, i.e., in PHP code, rather than in client-side Javascript.

Javascript, php, mysql, and json has me stumped

Been reading up on php and json and am trying this piece of code which is not working and I can't figure out why. Any help is appreciated.
I call a JavaScript function from my html file onLoad(). That function is
function getSched()
{
$.post("schedlz.php", {dat: ""+inputString+"", action: "searchSched"}, function(data)
{
var y="";
if(data.length >0)
{
var obj = JSON.parse(data);
y = getRes (data);
}
else //some error handler
}
function getRes(data)
{
var str="";
var obj = JSON.parse (data);
alert (data.length + " | " +obj + " | ");
return str;
}
In schedlz.php file
$conn = getDbConn();
mysql_select_db("myschedulez", $conn);
$result = mysql_query($sql,$conn) or die('Error: ' . mysql_error());
$rows = array();
while ($r = mysql_fetch_assoc($result))
{
// $rows['schedulez'][] = $r;
$rows[] = $r;
}
echo json_encode($rows);
mysql_close($conn);
The problem is that I get the data back in correct json format but when I parse it, there is no Object. What could be going wrong here?
You need to add the dataType parameter to your $.post, which in your case is json.
I'm also not sure if you closed $.post correctly in your sample so I'm adding the closing ); as well.
function getSched()
{
$.post("schedlz.php",
{dat: ""+inputString+"", action: "searchSched"},
function(data) {
var y="";
if(data.length >0)
{
var obj = JSON.parse(data);
y = getRes (data);
}
else {} //some error handler
},
'json'
);
}