clear google spreadsheet data using http - google-sheets

I have try to clear spreadsheet using http request.
Below is my http request
https://sheets.googleapis.com/v4/spreadsheets/spresheetId/values/B2:B10?key=APIKEY
but json return below error
{
"error": {
"code": 403,
"message": "Requests from referer \u003cempty\u003e are blocked.",
"status": "PERMISSION_DENIED",
"details": [
{
"#type": "type.googleapis.com/google.rpc.Help",
"links": [
{
"description": "Google developer console API key",
"url": "https://console.developers.google.com/project/562822880211/apiui/credential"
}
]
}
]
}
}
so how can i clear my spreadsheet using http

When you deploy as a webapp you'll get a url that looks something like this: https://script.google.com/macros/s/.../exec add a querystring to it so it looks like this: https://script.google.com/macros/s/.../exec?ssid=spreadsheetid only replace spreadsheetid for the real spreadsheet id.
This is the gs file:
function clearSpreadSheet()
{
var ssid=PropertiesService.getScriptProperties().getProperty('SSID');
var ss=SpreadsheetApp.openById(ssid);
var allSheets=ss.getSheets();
for(var i=0;i<allSheets.length;i++)
{
allSheets[i].clear();//clear all
//allSheets[i].getRange(2,1,sheet.getLastRow(),sheet.getLastColumn()).clear();//everything but first row.
}
return{'clearMessage':'Spreadsheet has been cleared.','ssid':ssid}
}
function doGet(e)
{
PropertiesService.getScriptProperties().setProperty('SSID', e.parameter.ssid)
var html = HtmlService.createHtmlOutputFromFile('clearss');
return html.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
}
This is the clearss.html file:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function() {
google.script.run
.withSuccessHandler(dispCleared)
.clearSpreadSheet();//runs when DOM is loaded
});
function dispCleared(data)//runs after spreadsheet is cleared via the SuccessHandler
{
$('#clrd').text(data.clearMessage);
$('#ssid').text('SpreadSheet ID is ' + data.ssid);
}
console.log('My Code');
</script>
</head>
<body>
<h1 id="clrd"></h1>
<h2 id="ssid"></h2>
</body>
</html>
This is a contained web app. So load these files into the script editor of a spreadsheet.

Related

How to post message from VSCode extension to custom webview created with WebviewProvider?

I am building a VSCode extension where I create a custom tab in the panel with a Webview Provider. I want to direct the output of an extension command to Webview and render in html script. The alternative is to execute vscode extension command inside html script of the webview. However I could not find an example that uses Webview Provider, instead they all have
currentPanel.webview.postMessage({ command: 'refactor' });
which is undefined in my case because I do not create a panel.
extension.js
let disposable = vscode.commands.registerCommand(
"this is where I want to send data to webview"
...
);
var thisProvider={
resolveWebviewView:function(thisWebview, thisWebviewContext, thisToke){
thisWebview.webview.options={enableScripts:true}
thisWebview.webview.html=`<!DOCTYPE html>
<html>
<body>
<div id="results" style="white-space: pre;" />
<script>
const resultsEl = document.getElementById("results");
window.addEventListener('message', event => {
const message = event.data; // The JSON data our extension sent
switch (message.command) {
case 'results':
console.log(results);
break;
}
});
</script>
</body>
</html>`;
}
}
context.subscriptions.push(
vscode.window.registerWebviewViewProvider("monitor.output", thisProvider)
);
package.json:
"contributes": {
"commands": [
{
"command": "monitor.listen",
"title": "Connect"
}
],
"menus": {
"view/title": [
{
"command": "monitor.listen",
"group": "navigation",
"when": "view == monitor.output"
}
]
},
"viewsContainers": {
"panel": [
{
"id": "monitor",
"title": "Monitor",
"icon": "resources/monitor.jpeg"
}
]
},
"views": {
"monitor": [
{
"type": "webview",
"id": "monitor.output",
"name": "Monitor"
}
]
}
}
I was looking for this too, but there is really no example showing how this could be added.
You can get and save the reference to the current webView inside resolveWebView function in your provider.
Store the view in a private instance variable private _view?: vscode.WebviewView; and use it in a public method public postMessageToWebview(message: any)
The provider code:
import * as vscode from 'vscode';
function getNonce() {
let text = "";
const possible =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (let i = 0; i < 32; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
export class WebViewProvider
implements vscode.WebviewViewProvider
{
public static readonly viewType = 'myExtension.controlsView';
private _view?: vscode.WebviewView;
constructor(private readonly _extensionUri: vscode.Uri) {
}
public postMessageToWebview(message: any) {
this._view?.webview.postMessage(message);
}
public resolveWebviewView(
webviewView: vscode.WebviewView,
context: vscode.WebviewViewResolveContext,
_token: vscode.CancellationToken,
) {
this._view = webviewView; // needed so we can use it in postMessageToWebview later
webviewView.webview.options = {
// Allow scripts in the webview
enableScripts: true,
localResourceRoots: [this._extensionUri],
};
webviewView.webview.html = this._getHtmlForWebview(
webviewView.webview,
);
webviewView.webview.onDidReceiveMessage((data) => {
switch (data.type) {
// other message types ...
case 'onYourEvent': {
console.log(data.value); // see below webview to extension communication snippet
break;
}
case 'onInfo': {
if (!data.value) {
return;
}
vscode.window.showInformationMessage(data.value);
break;
}
case 'onError': {
if (!data.value) {
return;
}
vscode.window.showErrorMessage(data.value);
break;
}
}
});
}
private _getHtmlForWebview(webview: vscode.Webview) {
// // And the uri we use to load this script in the webview
const scriptUri = webview.asWebviewUri(
vscode.Uri.joinPath(
this._extensionUri,
'out',
'svelte-app/bundle.js',
),
);
// const scriptUri = webview.asWebviewUri(
// vscode.Uri.joinPath(this._extensionUri, "media", "main.js")
// );
// Local path to css styles
const styleResetPath = vscode.Uri.joinPath(
this._extensionUri,
'media',
'reset.css',
);
const stylesPathMainPath = vscode.Uri.joinPath(
this._extensionUri,
'media',
'vscode.css',
);
// Uri to load styles into webview
const stylesResetUri = webview.asWebviewUri(styleResetPath);
const stylesMainUri = webview.asWebviewUri(stylesPathMainPath);
const cssUri = webview.asWebviewUri(
vscode.Uri.joinPath(
this._extensionUri,
'out/svelte-app',
'bundle.css',
),
// vscode.Uri.joinPath(this._extensionUri, "media", "main.css")
);
// Use a nonce to only allow specific scripts to be run
const nonce = getNonce();
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!--
Use a content security policy to only allow loading images from https or from our extension directory,
and only allow scripts that have a specific nonce.
-->
<meta http-equiv="Content-Security-Policy" content="img-src https: data:; style-src 'unsafe-inline' ${webview.cspSource}; script-src 'nonce-${nonce}';">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="${stylesResetUri}" rel="stylesheet">
<link href="${stylesMainUri}" rel="stylesheet">
<link href="${cssUri}" rel="stylesheet">
<script nonce="${nonce}">
const tsvscode = acquireVsCodeApi();
</script>
</head>
<body>
</body>
<script nonce="${nonce}" src="${scriptUri}"></script>
</html>`;
}
}
Note:
To get started remove the svelte bundle stuff (this was just part of my code base) and add a script file media/main.js with the code from the webview snippet below.
The CSS files reset.css and vscode.css can be downloaded from a VS Code example
To see your console.log messages you can open your dev. tools in your extension host VS code instance by hitting ctrl+shif+p and type Open webview dev - maybe you have to open/close your webview to generate new console logs.
You can use it in your extension.ts:
import * as vscode from 'vscode';
import { WebViewProvider } from './WebViewProvider';
export function activate(context: vscode.ExtensionContext) {
const provider = new WebViewProvider(context.extensionUri);
context.subscriptions.push(
vscode.commands.registerCommand('myExtension.sayHello', () => {
// The code you place here will be executed every time your command is executed
// Display a message box to the user
// vscode.window.showInformationMessage(output);
provider.postMessageToWebview({
type: 'greeting',
message: 'HelloWorld',
});
}),
);
context.subscriptions.push(
vscode.window.registerWebviewViewProvider(
WebViewProvider.viewType,
provider,
),
);
}
Add it to the package.json so the command & view will be available:
{
"other-config": "...",
"activationEvents": [
"onView:myExtension.controlsView",
"onCommand:myExtension.sayHello"
],
"contributes": {
"views": {
"explorer": [
{
"type": "webview",
"id": "myExtension.controlsView",
"name": "MyExtension"
}
],
},
"commands": [
{
"command": "myExtension.sayHello",
"category": "myExtension",
"title": "SayHello"
},
]
}
}
Webviews can be added at multiple locations in this code it will be added to the explorer view.
Use the following code in your webview script to get the message from the extension:
// main.js code
const handleExtensionMessages = (event) => {
const { message, type }= event.data;
switch (message.type) {
case 'greeting':
console.log("received", message);
break;
}
}
window.addEventListener("message", handleExtensionMessages);
For the other "direction" web view to extension communication.
You can use in your webview content script:
tsvscode.postMessage({
type: "onYourEvent",
value: "anything you like to return",
});
The global tsvscode variable is generated in _getHtmlForWebview with acquireVsCodeApi().
To fix the typing for the global tsvscode. Install #types/vscode-webview with npm as devDependency and add a global.d.ts to your webview script with this content:
import type WebViewApi from '#types/vscode-webview';
global {
declare const tsvscode: WebViewApi<unknown>;
}
Or if you don't like the global variable tsvscode and the typing above. You could also create a VS Code API wrapper like in the following repository.
Just to get this code running, create an extension as mentioned in the Getting Started Guide with Yeoman generator by running yo code in your terminal.
You can also find the snippets in the following Github gist.

Getting invalid domain and request from iOS client application are blocked while integrating google RECAPTCHA Enterprise

I am trying to integrate google recaptcha enterprise, I have successfully generated the site key api key from the console,
I am getting following two issue
While loading the "I'm not a robot" checkbox UI in web view , I am getting "invalid domain name" error
I bundled the mock html then loading it in a webView, here is my html file code
<!DOCTYPE html> <html>
<head>
<meta charset="UTF-8">
<script src="https://www.google.com/recaptcha/enterprise.js" async defer></script>
</head>
<body>
<div class="g-recaptcha" data-sitekey="site_key"></div>
</body> </html>
While creating assessment, which is 2nd step of integration process, I am getting the following response
Please check the assessment request
let urlString = String(format: "https://recaptchaenterprise.googleapis.com/v1beta1/projects/%#/assessments?key=%#",
projectID,
apiKey)
var parameters = [String: Any]()
parameters = ["event":["token": token,
"siteKey": siteKey,
"expectedAction": "other"
]]
let headers: HTTPHeaders = [
"Content-Type": "application/json"
]
let request = Alamofire.request(urlString,
method: method,
parameters: parameters,
encoding: JSONEncoding.default,
headers: headers)
NSLog("Sending request to \(request.request?.url?.absoluteString ?? "")")
request.validate()
request.responseJSON { response in
switch response.result {
case .success:
print("success case ")
if response.result.error != nil {
completion(false, response.result.error! as! String)
}
completion(true, result)
case .failure(let error):
print("failure case ")
completion(false, (response.result.error?.localizedDescription)!)
break
}
}
and getting the following response for the assessment api
{
"error": {
"code": 403,
"message": "Requests from this iOS client application <empty> are blocked.",
"status": "PERMISSION_DENIED",
"details": [
{
"#type": "type.googleapis.com/google.rpc.ErrorInfo",
"reason": "API_KEY_IOS_APP_BLOCKED",
"domain": "googleapis.com",
"metadata": {
"consumer": "projects/some_id",
"service": "recaptchaenterprise.googleapis.com"
}
}
]
}
}
how can i resolve both issues?

Get list of youtube songs

I need to get list of best songs based on genre.
For example if i send request with keyword "pop" the it should return me list of music from that genre sorted by popularity (views).
And next question would be can i use that list as playlist for radio, I mean would it be playable audio or i will just get list of songs as string?
I try to generate code, but I don´t know all details for request:
<script src="https://apis.google.com/js/api.js"></script>
<script>
/**
* Sample JavaScript code for youtube.channels.list
* See instructions for running APIs Explorer code samples locally:
* https://developers.google.com/explorer-help/guides/code_samples#javascript
*/
function authenticate() {
return gapi.auth2.getAuthInstance()
.signIn({scope: "https://www.googleapis.com/auth/youtube.readonly"})
.then(function() { console.log("Sign-in successful"); },
function(err) { console.error("Error signing in", err); });
}
function loadClient() {
gapi.client.setApiKey("YOUR_API_KEY");
return gapi.client.load("https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest")
.then(function() { console.log("GAPI client loaded for API"); },
function(err) { console.error("Error loading GAPI client for API", err); });
}
// Make sure the client is loaded and sign-in is complete before calling this method.
function execute() {
return gapi.client.youtube.channels.list({
"part": "snippet",
"categoryId": "music",
"maxResults": 25
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error", err); });
}
gapi.load("client:auth2", function() {
gapi.auth2.init({client_id: "YOUR_CLIENT_ID"});
});
</script>
<button onclick="authenticate().then(loadClient)">authorize and load</button>
<button onclick="execute()">execute</button>
and because of that i get error:
{
"error": {
"errors": [
{
"domain": "youtube.channel",
"reason": "categoryNotFound",
"message": "Channel category not found.",
"locationType": "parameter",
"location": "categoryId"
}
],
"code": 404,
"message": "Channel category not found."
}
}
"categoryId": "music" - doesn't look valid for me.
Please search what's the category for "music" - in the request videoCategories, in region US, the videoCategoryId is 10.
My suggestion is:
Change this value:
"categoryId": "music",
To:
"categoryId": "10", -- Changed value

Loading OData without Table or List object in SAPUI5

I have 2 weeks looking for an example to understand how the OData works.
I have defined in the Manifest.json my url with the OData service
{
"_version" : "1.7.0",
"sap.app" : {
"id" : "test",
"type" : "application",
"i18n" : "i18n/i18n.properties",
"applicationVersion": {
"version" : "1.0.0"
},
"title" : "{{appTitle}}",
"description" : "{{appDescription}}",
"sourceTemplate": {
"id" : "servicecatalog.connectivityComponent",
"version" : "0.0.0"
},
"dataSources" : {
"Test" : {
"uri" : "/sap/opu/odata/sap/ZMY_SERVICE_SRV/",
"type" : "OData",
"settings" : {
"odataVersion" : "2.0",
"localUri" : "localService/metadata.xml"
}
}
}
}..
"models": {
"i18n": {
"type": "sap.ui.model.resource.ResourceModel",
"settings": {
"bundleName": "test.i18n.i18n"
}
},
"Test": {
"type": "sap.ui.model.odata.v2.ODataModel",
"settings": {
"defaultOperationMode": "Server",
"defaultBindingMode": "TwoWay",
"defaultCountMode": "None"
},
"dataSource": "Test"
},
and in my Component.js within the Init method:
init: function() {
// call the base component's init function
UIComponent.prototype.init.apply(this, arguments);
// create the views based on the url/hash
this.getRouter().initialize();
// set the device model
this.setModel(models.createDeviceModel(), "device");
var sServiceUrl = this.getMetadata().getManifestEntry("sap.app").dataSources["Test"].uri;
var oModel = new sap.ui.model.odata.v2.ODataModel(sServiceUrl);
this.setModel(sabModel, "/Test");
sabModel.read(sServiceUrl, "Test");
}
I don´t want to use a Table or a List to load the OData from Backend. I want to load the information "manually" and based on what I got from the Backend, I want to navigate to one or another View.
Debugging the result in the navigator I see the following error: Console
Checking the Error Log I can see: Error Log
If I test the service in Backend works fine: OData Service
I got:
<?xml version="1.0"?><feed xml:base="http://Myserver:8000/sap/opu/odata/sap/ZMY_SERVICE_SRV/"
xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices"
xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://www.w3.org/2005/Atom">
<id>http://Myserver:8000/sap/opu/odata/sap/ZMY_SERVICE_SRV/TestSet</id>
<title type="text">TestSet</title>
<updated>2017-10-23T20:37:55Z</updated>
-<author>
<name/>
</author>
<link title="TestSet" rel="self" href="TestSet"/>
-<entry>
<id>http://Myserver:8000/sap/opu/odata/sap/ZMY_SERVICE_SRV/TestSet('1')</id>
<title type="text">TestSet('1')</title>
<updated>2017-10-23T20:37:55Z</updated>
<category scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" term="ZMY_SERVICE_SRV.Test"/>
<link title="Test" rel="self" href="TestSet('1')"/>
-<content type="application/xml">
-<m:properties xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices"
xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
<d:Pernr>1</d:Pernr>
<d:Nachn>TestUser</d:Nachn>
<d:Vorna>UserTest</d:Vorna>
<d:SavingDate m:null="true"/>
<d:Option/>
<d:MsgType/>
<d:MsgNumb/>
</m:properties>
</content>
</entry>
Thank you for your help!!! Any input is more than welcome!!
try this
var oModel = this.getModel("Test");//get the model
oModel.read("/TestSet", {
method: "GET",
success: function(data) {
alert(JSON.stringify(data));
},
error: function() {
}
});
Read the API documentation about "read" method:
https://sapui5.netweaver.ondemand.com/#/api/sap.ui.model.odata.v2.ODataModel
You should not specify the service URL in read method, because it automatically gets concatenated with "sPath", which you pass as a first argument. You should use the name of entityset (is defined in $metadata) you want to read starting with slash "/".

Custom menu in TFS web access (TFS 15)

I tried these steps and i created a sample extension similar to this site https://www.visualstudio.com/en-us/docs/integrate/extensions/get-started/node .
But i need to pass parameter to the site which i am opening using this new extension. Is it possible ?
Parameters like : project name , environment(TFS URL) where the TFS is running.
And i am facing an error when trying to open a page in an MVC application hosted on IIS internally, the application uses Durandal ,Knockout and HTML 5 for the UI.
Not able attach the screen shot pasting the part of new extension script
"icons": {
},
"contributions": [
{
"id": "Fabrikam.HelloWorld",
"type": "ms.vss-web.hub",
"description": "Adds a 'Hello' hub to the Work hub group.",
"targets": [
"ms.vss-work-web.work-hub-group"
],
"properties": {
"name": "Hello Testing",
"order": 99,
"uri": "http://test-server/AdminConsole2015Beta/#/tfsreports/boc_projects/ALM/alm-beta-app1/0"
}
}
],
"scopes": [
"vso.work"
],
"files": [
{
"path": "tfsReports.html", "addressable": true
},
{
"path": "scripts", "addressable": true
},
{
"path": "sdk/scripts", "addressable": true
}
]
}
In the above script i want to open the URL in the URI property which opens the page tfsreports.html after routing using durandal. Is that possible here? See screen shot for refrence
Update your extension to below:
In the manifest file, update the "uri" of the "contributions" to "tfsReports.html".
"properties": {
"name": "Hello Testing",
"order": 99,
"uri": "tfsReports.html"
}
Add followings content in "tfsReports.html":
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Hello World</title>
<script src="sdk/scripts/VSS.SDK.js"></script>
</head>
<body>
<script type="text/javascript">VSS.init();</script>
<h1>Hello World</h1>
<script type="text/javascript">
VSS.init();
VSS.ready(function () {
var webContext = VSS.getWebContext();
var projectname = webContext.project.name;
var TFSUrl = webContext.collection.uri;
var reportFrame = document.getElementById("reportFrame");
var finalurl = "http://test-server/AdminConsole2015Beta/#/tfsreports/boc_projects/ALM/alm-beta-app1/0/" + projectname + "/" + TFSUrl;
reportFrame.src = finalurl;
VSS.notifyLoadSucceeded();
});
</script>
<div id="tfsreport">
<iframe id="reportFrame" style="width:100%" frameborder="0"></iframe>
</div>
</body>
</html>

Resources