SuiteScript how to call a backend Suitelet - suitescript

I have looked at the other posts and none directly show this. I need to call a backend Suitelet from a userevent. I have created a generic backend suitelet that I need to call from multiple events, I have tried SS2 to call using https with a full qualified and a relational Suitelet URL and niether seems to work. The full qualified seems to go without error but then after the request does not enter the catch I put in place it veers off into NS library code and doesn't seem to call the Suitelet. Any help would be greatly appreciated. I have included code os the call.
var url = 'https://debugger.sandbox.netsuite.com/app/site/hosting/scriptlet.nl?script=1239&deploy=1';
var header = [];
header['Content-Type']='application/json';
var response = https.post( {
url : url
, header: header
, body : {
data: id
}
} );

You can only successfully call a Suitelet, which is available without login, from a server-side script. A Suitelet, which is not available without login, can be called from a client script as on client-side the authenticated session already exists. Perhaps a RESTlet would serve your scenario better? You can pass authentication headers when invoking the RESTlet. Otherwise, a custom module could hold the logic and be invoked from the different scripts.

Related

FlowRouter, how to get data when routing depends on subscription

I'm writing a licence validation part for my application and want to redirect the user to a renewal page if and only if their licence has expired.
I am using FlowRouter and Blaze.
All my authenticated routes are in a group:
let authenticated = FlowRouter.group({
triggersEnter: [checkAuthenticated, checkSubscription]
});
I then check if the subscription is valid like so:
const checkSubscription = function(context){
let path = FlowRouter.current().path;
if (!Meteor.userId()){
return;
}
const sub = new Subscription();
if (sub.isInvalid() && path !=="/manage-practice/subscription"){
FlowRouter.go("/manage-practice/subscription");
}
};
My class subscription uses a collection that I can only load once a user has logged in. My problem is that the router usually triggers this redirection before this data has been loaded.
Is there a best practice approach to solve this?
Redirect with Triggers
I'm not sure about this being 'best practice' but one approach is to use the Flow Router redirect functionality on your login event.
You can see examples at: https://atmospherejs.com/kadira/flow-router#redirecting-with-triggers and https://github.com/meteor-useraccounts/flow-routing.
The initial login path (using Accounts.onLogin();) could be to a generic 'loading...' template while you evaluate the user's collection. On a callback you can then use the custom redirect function to either redirect to the requested page in your app, or redirect the user to your '/manage-practice/subscription' path.
FlowRouter.wait()
I have to confess I wasn't previously familiar with this second option, but I've just come across FlowRouter.wait(). This can be useful to delay the default routing process until some other evaluation is complete. I suspect this might only be relevant if a user logs directly into a page within your authenticated routing group.
Documentation: https://atmospherejs.com/kadira/flow-router#flowrouter-wait-and-flowrouter-initialize

How does SoapUI bypass CORS issue when my ajax call can't do it?

This might be a silly question but here is my simple webapi 2 method
public class ProductsController : ApiController
{
Product[] products = new Product[]
{
new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
};
public IEnumerable<Product> GetAllProducts()
{
return products;
}
Now if I run it , on my pc it runs on http://localhost:3145/Products, and I can see the products as XML
It also works using soapui
But now if I try to access this with a html file and this javascript
<script type="text/javascript">
function GetProducts() {
$.ajax({
url: "http://localhost:3145/Products",
dataType: "json",
success: function (data) {
for (var i = 0; i < data.length; i++)
$('#myDiv').append(data[i].Category).append("<br/>");
},
error: function (xhr, status) {
alert(xhr);
}
});
}
</script>
</head>
<body onload="GetProducts()">
<h1>My App</h1>
<div id="myDiv"></div>
I get the CORS error
How is SOAP UI not getting an error here when it is using http as well?
Thanks
Put that index file into some server location, and then browse the page with server url , like, http://localhost/virtual_dir/index.html , else it will say it file:/// domain does not match with http://localhost:port . And you might face CORS issue if you deploy this page to some other domain and start using.
I have seen that you are using webapi , and you might face CORS issue if you place you JS in domain ( "example1.com"), i mean files served from example1.com will have ajax calls to webapi and that webapi may be hosted in example2.com. This will raise CORS issue. Browser restricts ajax call to other domains, unless that domain allow you to invoke. To achieve this, you can follow this link - Angular.js $resource with ASP.Net webapi? (don't go by the title)
I have answered there the same scenario.
I just experienced the same situation with a web page I was developing that needed to send a SOAP request to a web service that was served by a remote server that was not CORS-enabled. This was in a test environment; in production, the web page and web service are served from the same domain and port.
How is SOAP UI not getting an error here when it is using http as well?
Yes, SoapUI and a web browser both use HTTP. But SoapUI is not a web browser, and does not share the same restrictions.
A colleague solved this issue for me by pointing me to CORS Anywhere.
Install Node.js, if you don't already have it.
Install CORS Anywhere (npm install cors-anywhere).
Run CORS Anywhere (node cors-anywhere.js).
Instead of using your original non-CORS-enabled web service URL, use the domain and port in the resulting message from CORS Anywhere ("Running CORS Anywhere on ..."), with your original web service URL as the path component.
You can specify the CORS Anywhere port in an environment variable (or edit the default value in your local copy of cors-anywhere.js).
In my case, the production web service URL is hardcoded in the web page as a relative path. But I've added code that reads a URL from a parameter in the fragment identifier ("hash string"), overriding the default web service URL.
For example:
http://localhost:8081/mywebpage.html#url=http://localhost:8089/remote.domain.com:8085/servicename
where:
http://localhost:8081/mywebpage.html is my web page (I'm using http://, not file://, for this).
http://localhost:8089 is the CORS Anywhere proxy.
remote.domain.com:8085/servicename (you can drop the leading http://) is the remote, non-CORS-enabled web service.
I could point you 2 options to solve this:
Disable your browser CORS: Due the CORS enforcement is done by the browser you can just disable this during development in yourself browser. If you use Chrome, you must just set an parameter otherwise I may guess looking to the underneath image you are using Firefox, for this you have an extension to do this: https://addons.mozilla.org/pt-PT/firefox/addon/cors-everywhere/
Allow CORS in SOAP UI: It can take a little bit more effort than above solution but it fits very good when you need to share with mutiple teammates or just to make the solution attached to the mock service. To do this,you must add a response for the root of resource path that responds to OPTIONS and with headers you need for CORS with status 204 (or 200).
After, in the MockService you just need to add a script to grab these same headers in all calls that passes through.
Here is the article to solve this step-by-step:
https://medium.com/#andrelimamail/how-to-deal-with-cors-in-soap-ui-mock-services-or-anyother-f4cc55b3dccd

Performing redirects in ServiceStack

I'm attempting to build a service in ServiceStack whose sole responsibility will be to interpret requests, and send a redirect response. Something like this:
[Route("/redirect/", "POST")
public class Redirect : IReturnVoid
{
public string Something { get; set; }
}
public class RedirectService : Service
{
public object Post(Redirect req)
{
// make some decisions about stuff
return new HttpResult(){ StatusCode = HttpStatusCode.Redirect, Headers = {{HttpHeaders.Location, "place"}}};
}
}
I did initial testing using fiddler, setting a content-type of application/json and creating an appropriate request body.This did exactly as expected: the service request gave a 302 response and redirected to the expected location.
I've also tested this by using a basic Html form post, with an action of http://myserviceuri/redirect/, which also works as expected and redirects appropriately.
However, i've hit an issue when attempting to use the SS c# client to call the same service. If I call the following code in an aspx code behind or an mvc controller
var client = new JsonServiceClient("uri);
client.post(new Redirect{Something = "something});
I get a 500 and the error message:
The remote certificate is invalid according to the validation procedure.
Which makes sense as it's a development server, with a self-cert. But I get the feeling that, as I can call the service successfully by other means, that this is a red herring.
Should I be using a different type of c# client to make the request, or setting any more custom headers, or something else? Am I fundamentally not understanding what i'm trying to do?
Please let me know if more info is needed. Thanks.
What's happening here is that the JsonServiceClient is happily following the redirect, doing more than what you've expected it to do.
I'll reference a related question and answer for posterity ( - hopefully you've resolved this issue a long time ago...).
POST to ServiceStack Service and retrieve Location Header
Essentially you'd use .net's WebRequest or the ServiceStack extensions mentioned in the answer to see the redirect and act as you see fit.

Call an asp.net page (ashx handler) from a different asp.net page

I have a admin page in asp.net that adds data to a database. This database is available as a JSON string to external websites, however, since it's a lot of data, the external websites cache this data locally.
I want to be able to ping the external websites to let them know the data has changed so they can referesh their cache. I figure I can setup an ASHX handler that receives a parameter telling them what data has changed, so they can both delete that data and refresh it.
The only part I'm not sure about is the best way to call this external page from my admin page. Do I just do a regular WebRequest and discard the result? or is there a simpler way to call a page from code when you don't need the response?
Basically I just want to "ping" this page, so it knows it needs to refresh.
thanks!
If you just want to call the remote page, you can use the WebRequest class.
http://msdn.microsoft.com/en-us/library/debx8sh9.aspx
WebRequest request = WebRequest.Create("http://my.domain.ext/page.ashx");
using(WebResponse response = request.GetResponse()) {
response.Close();
}
If you want to do more advanced stuff a webservice would be more appropriate.
You could have a flag set up in the database. That would turn this into a much simpler task.
If no alternative exists you can use the WebClient class:
using (var wc = new WebClient())
{
wc.DownloadString(address);
}

Handling redirected URL within Flex app?

We have a Flex client and a server that is using the Spring/Blazeds project.
After the user logs in and is authenticated, the spring security layer sends a redirect to a new URL which is where our main application is located.
However, within the flex client, I'm currently using HTTPService for the initial request and I get the redirected page sent back to me in its entirety.
How can I just get the URL so that I can use navigatetourl to get where the app to go where it needs to?
Any help would greatly be appreciated. Thanks!
One solution would be to include a token inside a comment block on the returned page, for instance:
<!-- redirectPage="http://localhost/new-location" -->
then check for it's presence inside the HTTPService result handler. The token's value could then be used in your call to navigateToURL.
Another solution would be to examine the HTTP response headers and extract the value of the "Location" header using ActionScript. Consider using the AS3 HTTP Client lib.
From the examples page http://code.google.com/p/as3httpclientlib/wiki/Examples To determine the 'Location' header from the response:
var client:HttpClient = new HttpClient();
var uri:URI = new URI("http://localhost/j_security_check");
client.listener.onStatus = function(event:HttpStatusEvent):void {
var response:HttpResponse = event.response;
// Headers are case insensitive
var redirectLocation:String = response.header.getValue("Location");
// call navigateToURL with redirectLocation
// ...
};
// include username and password in the request
client.post(uri);
NOTE: AS3 HTTP Client depends on AS3 Core and AS3 Crypto libs.
You can also simply use the URLLoader class, no need for external code. One of the events it dispatches is HTTPStatusEvent.HTTP_RESPONSE_STATUS. Just plug into that and retrieve the redirected url:
urlLoader.addEventListener(HTTPStatusEvent.HTTP_RESPONSE_STATUS, onHTTPResponseStatus);
private function onHTTPResponseStatus(event:HTTPStatusEvent):void
{
var responseURL:String = event.responseURL;
}
I am (successfully) using this code right now, so if it doesn't work for some reason, let me know.

Resources