Service Now Api integration using client side script - api

I tried to integrate external soap based api using servicenow client side scipt options. My intention is to initiate an external api call when an incident is created.
But i am getting uncaught reference error sn_ws is not defined exception.
function onSubmit() {
try {
var s = new sn_ws.SOAPMessageV2('global.IQTrack', 'VerifyApiKey');
s.setStringParameterNoEscape('VerifyApiKey.apiKey', 'dfghdhgdjh');
var response = s.execute();
var responseBody = response.getBody();
var status = response.getStatusCode();
}
catch(ex) {
alert(ex);
}
}
Is this the way to initiate api call? If it is so why it is getting sn_ws is not defined.

That's because sn_ws is a server-side API.
You need to either use GlideAjax, or a client-side webservices API such as XMLHttpRequest.
You can find an excellent article on GlideAjax, here: http://snprotips.com/blog/2016/2/6/gliderecord-client-side-vs-server-side
If your aim is to initiate the message once a ticket is created, then you should definitely be doing this server-side, not in a client script.

I hope,sn_ws is a server-side API.
I think GlideAjax method will help you to get rid of this issues.
please go through below links,I think it will help you to sort out this issues.
http://wiki.servicenow.com/index.php?title=GlideAjax#gsc.tab=0
And alternative is use client-side webservices API like XMLHttpRequest

Related

Create a space with Google Chat REST API

We have a program that uses a service account to manage various thing inside Google Chat.
Now, we have the need to create a new space using the Google Chat REST API (spaces.create).
We already joined the developer preview program, as this endpoint is not yet generally available.
From what we understand, this endpoint is not possible to invoke via service account and so we wanted to ask you… can we invoke this endpoint automatically using “domain delegation”? If yes, how?
We always want to use the service account as it is not possible to show a login prompt to the user.
We enabled the domain delegation but that endpoint returns always status 403. (We are using Google.Apis library for .NET Core
using Google.Apis.Auth.OAuth2;
var credential = GoogleCredential.FromFile("key.json")
.CreateScoped("https://www.googleapis.com/auth/chat.spaces.create")
.CreateWithUser("service-account-email#project.iam.gserviceaccount.com");
var token = await credential.UnderlyingCredential.GetAccessTokenForRequestAsync();
HttpRequestMessage request = new(HttpMethod.Post, "https://chat.googleapis.com/v1/spaces");
request.Headers.Authorization = new("Bearer", token);
var payload = #"
{
""name"": ""testspace-1"",
""spaceType"": ""SPACE"",
""singleUserBotDm"": true,
""displayName"": ""Test Space""
}
";
request.Content = new StringContent(payload, System.Text.Encoding.UTF8, "application/json");
HttpClient client = new();
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
If you check the documentation Auth
You will notice it stats that service account authorization is supported. If you are part of thedeveloper preview program
The reason I asked about your code is that the last time i tried this which notably was a while ago. The google .net client library was not generated the methods that were under preview.
So while it may work yes. The issue your may have is that the client library when loaded will not have the method you need meaning you will have to code the call to the endpoint yourself.
If this is in fact the case let me know if you have any issues peceing it together I may be able to help.
update your code
There is an error in your code
.CreateWithUser("service-account-email#project.iam.gserviceaccount.com");
The email in CreateWithUser should be the user on your domain who you wish to delicate the service account as. Not the service account email address.

Failed to update Salesforce account because of DUPLICATES_DETECTED error even with Allow setting in Duplicate Rule

I'm using JSforce to integrate Salesforce into my app. When I update a Salesforce account from my end via JSforce update function, it got DUPLICATES_DETECTED error because Salesforce considers this account is duplicate with another one. Although I set Allow in Duplicate rule setting of the Salesforce page and we can edit successfully this account on it, It cannot be done via API (with using JSforce) from my end because of this error. Is this possible to bypass Duplicate Management via JSforce without disabling these rules?
const jsforce = require('jsforce');
/* Update to Salesforce */
update: function (updateObject, callback) {
this.getSObject().update(updateObject, callback);
}
Some documents suggest setting allowSave to true in header of request via API soap like this but I don't use API soap, I'm using JSforce instead.
You just got possibility to do this in REST API, which jsforce uses.
You can do it this way:
sfConnection.sobject("Account").create(mappedAccounts, {
allowRecursive: true,
headers: {
'Sforce-Duplicate-Rule-Header': 'allowSave=true'
}
});
This is not explicitly explained in documentation, but you can figure it out from their code.
Other possible values you can find here: https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/headers_duplicaterules.htm

Pre-initialise a website from another site

I have two websites, one client website and a pricing WEBAPI website. I have a performance issue with the pricing website as it often suspends itself due to low usage and on the first call takes time to initialize. If I repeat the request immediately after that, it is very quick.
I know that it will be used on certain pages of the client website, I therefore wish to call it when that page loads so its ready when the users valid request comes in seconds later. Please note the pricing WEBAPI site is not available from the client, only the client website can access it on the server side.
I don't know the best approach to this, I don't wish to impact the performance of the client website. I have considered an 1px x 1px iFrame calling a page but concerned it will block the page. Is an Ajax call more appropriate, but how to I call something on the client website to in turn call the webservice? Is there a better approach I haven't considered?
Known issue on shared hosting environments, a workaround is fine but I would suggest upgrading your server. My hosting has a DotNetNuke option, which essentially means it will reserve memory on the server and don't recycle the app pool due inactivity. Compared to VPS this is cheaper.
If it is not shared hosting, these IIS settings could help you.
Anyway, back to your workaround:
You say the client cannot access the webapi, only the back-end of your website can. Seems weird because an webapi exposes REST GET,POST methods. Either way you could do an async call to your webapi on server side that does not wait for a response or do a javascript call to your API.
Assuming your website is also ASP.NET:
public static async Task StartupWebapi()
{
string requestUrl = "http://yourwebapi.com/api/startup";
using (var client = new HttpClient())
{
//client.Timeout = new TimeSpan(0, 0, 20); timeout if needed
try
{
HttpResponseMessage response = await client.GetAsync(requestUrl);
if (response.IsSuccessStatusCode)
{
resultString = await response.Content.ReadAsStringAsync();
}
}
}
}
Then, somewhere in your code, that will be called at least when your client website starts.
HostingEnvironment.QueueBackgroundWorkItem(ct => SomeClass.StartupWebapi());
Or in javascript, which is executed asynchronously.
$.ajax({
url: "http://yourwebapi.com/api/startup",
type: "GET",
success: function (response) {
},
error: function (response) {
}
});
See this question for some other workarounds.

Apigee Api proxy - how to make asynchronous call

I have api that I would like to return to user as soon as the message is received by apigee. Do not wait for response from my service. Do you know how to do that using apigee api proxy?
The node.js method mentioned above is probably the most straight forward solution. Information on using node.js with Apigee can be found at http://apigee.com/docs/api-services/content/developing-nodejs-applications-apigee-edge
I believe you tried the initial right approach Kaszaq using httpClient get method. As it's been documented in Apigee Docs.
http://apigee.com/docs/api-services/content/javascript-object-model
https://github.com/apigee/api-platform-samples/blob/master/sample-proxies/async-callout/apiproxy/resources/jsc/callout.js
And yes, if you want a more robust solution try Node.js.
//
// Make 5 HTTP callouts to Yahoo weather to get the weather for 5 cities
// The calls are all asynchronous and execute in parallel
// httpClient returns an exchange object that will contain the HTTP response. . . when it arrives
//
var paloAlto = httpClient.get('http://weather.yahooapis.com/forecastrss?w=2467861');
context.session['paloAlto'] = paloAlto;
var anchorage = httpClient.get('http://weather.yahooapis.com/forecastrss?w=2354490');
context.session['anchorage'] = anchorage;
var honolulu = httpClient.get('http://weather.yahooapis.com/forecastrss?w=2423945');
context.session['honolulu'] = honolulu;
var newyork = httpClient.get('http://weather.yahooapis.com/forecastrss?w=2459115');
context.session['newyork'] = newyork;
var dublin = httpClient.get('http://weather.yahooapis.com/forecastrss?w=560743');
context.session['dublin'] = dublin;
As you have the liberty of customising API's using Node.js. You can use that to implement async behaviour in you api proxy.
For more info on customising api's using Node.js visit the following link-
http://apigee.com/docs/api-services/content/developing-nodejs-applications-apigee-edge

Send data to a REST API every time a new account is added to Salesforce

Sorry for the total newbie question here regarding triggers, but here is my scenerio:
What are some of the options available to send data to a 3rd party REST API every time a new account is added to Salesforce?
I have been initially looking at code examples for triggers on account after insert. In addition to this, is there a way using the SFDC streaming API? Any ideas on What API usage is best practice + code examples would be much appreciated.
Thanks in advance!
To be able to make callout from a trigger you need to make the callout asynchronous (using #future annotation) .
For example :
trigger AfterInsertAccount on Account (after insert){
futCls.asynchCallout(); //call a method with #future annotation
}
Class Code :
global futCls {
#future
Public static void asynchCallout(callout=true){
HttpRequest req = new HttpRequest();
req.setEndpoint('your 3rd party service URL goes here');
req.setMethod('GET');
Http http = new Http();
HTTPResponse res = http.send(req);
}
}
For more information refer to SFDC documentation.