logo

NJP

NOWCommunity Live Stream - Code Decoded - Using a Constants script include

Import · Jul 20, 2020 · video

[Music] good morning good afternoon good evening wherever you are and whenever you are welcome to the community live stream this is the show that gives you the insights the background the reverse engineering all that fun stuff that you can take to be a better service now administrator developer my name is chuck tomasi this is july 20th and our topic today is about constance script includes i've touched on this before it may have been blended into one of the earlier episodes that was a composite of things that we did on i'm going to bring it out and make it explicit today and show you exactly what we're going through and why with examples so stick with me we're going to do this to make your scripting easier to maintain okay that's the idea it's worked well for me for the past year or so and i want to share this with you because you know obviously we all want to do less maintenance and go on do other fun stuff thank you everyone for joining me i see names popping up in the chat live on youtube this is uh let's see raul allen john steve steve this is your question so pay attention today it was inspired by steve from sweden we've got mark and ryaz thank you everybody who's checking in go ahead and subscribe turn on those notifications like share you know do the youtube thing it's it's been around for a while i'm sure you all wouldn't know what to do when you get this so again a lot of people checking in thank you very much we also do this as a backup plan because as we all know technology isn't flawless the internet deities do what they do uh to sometimes turn into internet demons and and things go a little sideways pear-shaped awry whatever you want to call it that happens so we use twitch as a backup you can find that content for a couple of weeks there if things really go terribly sideways like maybe the the wirecast application crashes well then we're going to just have to deal with it and move on stay on the youtube stream if that happens because i can always reconnect even through a reboot the stream is up so i'll be right back and then if you're watching anyway let's hope that doesn't happen today let's get on with the content that's what we came here for we want to talk about some cool stuff let's see uh let's get through the rest of the pre-roll go over to the developer site developer.servicenow.com and get yourself a free personal developer instance we are only days away as of this recording from having access to paris early access on these instances getting very excited this is like christmas time twice a year servicenow brings you christmas time so you can you can open up your package and see what santa claus brought you with all the uh wonderful toys in paris i've got my social media picture already of my family in front of the eiffel tower from a family trip a couple of years ago we'll roll that out and have some fun with that too i'm sure so paris is our latest release we name them after the cities of the world starting with aspen and now we're up to p about every six months so q1 and q3 is when you can find those and it is q3 and it is early access time looking very much forward to digging into those wow lots of good mornings rolling in i can't even keep up anymore thank you thank you if you have a question that goes beyond just the script include topic that we're talking about today we are going to be focusing on script includes so be sure to keep your questions in the live chat appreciate them very much keep them focused on that topic or if you guys want to have a sideline discussion that's fine too but if it goes beyond that please post that in the community there are hundreds of thousands of people there that can help you out with that i've been reading some really good answers from very smart people whether it's developer focused on scripting or it's performance and analytics and security lots of different subforums in the community that you can post to to get your questions answered to get your issues resolved it's a great place to go highly encourage you to pick that up observe what's going on like any other community any other online community you want to understand what the etiquette is what should you put in your signature what shouldn't you put in your signature that kind of thing and then feel free to start posting be sure to search before you go in there because chances are if you've got a a newbie question let's call it that i'm being polite i say that lovingly if you've got a new question search for the answer if you don't find it then you can of course make a post so typical community stuff also over at meetup.com i have that available we have developer meetups going on currently i'll be attending the boston i think it's boston tonight let me check boston july 20th yes boston meetup is tonight if you happen to be around at the appropriate time zone check it out i'll do my best to be there unless some emergency comes up that's my plan so look for that you can join one of the other 62 chapters around the globe there's a lot of them go over to meetup.com pro slash servicenow dev program and get together with like-minded people i had somebody ask me on linkedin i would love to get together with people with other servicenow developers and discuss this is the place they're already there they're waiting for you so sign up be an organizer if there isn't a chapter in your area even if it's not in your area i'm not in boston but i'm going to attend boston because it's close enough to my time zone and i can do that so a lot of good uh information exchange going on there we also have i want to socialize this to you one more time we are about a week away from our tech now on the paris platform features so look for that it's also on a side banner in the developer community portion of the community we're going to have a banner on the developer site pretty soon so hopefully you won't miss out on that register at the bitly link you see there tn 77 reg make it easy for you instead of remembering this big convoluted lp equals five digit number blah blah blah keep it simple and you can register thank you very much for joining for that i'm really looking forward to going through and sharing that information with you asap we will be doing some javascript today and if you are not comfortable with javascript then i encourage you to go check out the video series that i put together totally free walk through it at your own pace short little segments about each topic and use the bitly link you see there sn-learn js to go learn more about javascript and advance your career as a servicenow developer i will be writing a little bit of script today and putting that into a github repo for you to download and share and look at and experiment and try and do and say why isn't mine working but chucks did well we can go and compare notes this way so this is just a little user contributed solution that you can find in a dated folder this one's going to be fun because it's 2020 so year month day format for each folder that i do these on the show can you take a session for scenarios of modules modules as in the navigation modules on the side love to if that's what you're talking about abhishek i will make a note of that actually do me a favor send me like a linkedin message or an email so that i remember it because sometimes when i say things in these streams i don't remember 20 minutes later let alone an hour later to take it down and i don't want to stop and you know go over and log into my app that tracks all these ideas love the idea i spend two hours on friday putting together ideas for this show so i've got about a year's worth of content lined up for you uh maybe two years of account right two years in the idea backlog that uh we've got a lot of content to cover but i i will be putting in if you've got a request i will bump that up higher in the the lineup and say hey that's gonna go that's how it happened with steve steve said could you you showed me that thing where you put constants in a script include could you show that to us today and i said yeah i'll get to it in a couple of weeks so i had to put together some notes some examples what i want to talk about and here we go let's get started i've gotten through the pre-roll no technical issues going on so much thank you very much for uh promising to send me an email or a linkedin message you can you can reach me there used to be we had sort of a dm a direct message private message capability on the um on the community i haven't seen that come back but hopefully it's in the idea pool somewhere okay we ready to go let's get started so i want to start with i got to back up here i'm not going to jump right into what steve asked me because that would be a little advanced for some of you who haven't done servicenow scripting for some time or maybe not at all so i want to start with this concept of what is a script include it is a server-side library of code of settings of javascript that you can reuse in other areas of the server-side platform because servicenow has client scripting that gets sent to your browser many of you who've done javascript on other platforms are familiar with this things like enabling or disabling fields or changing the colors you know client-side stuff usually happens immediately so when i change this field something else reacts to it that's that's the client side javascript well server side script is uh something very very powerful that i didn't quite understand because i like many of you i came from another platform before servicenow and i understood client side script pretty well did json stuff and manipulated some objects on the screen but server side gives you the ability to talk to the database it gives you some advanced functions that you can use a lot of coding your preference should be towards server side before thinking about client side if you've got a problem to solve think about serving solving it server side they each have their distinct use cases and there are some places where there's overlap and when given the choice go to server side well given the choice do no scripting use something like flow designer that doesn't need scripting but when you've got to do scripting think about server side first and rather than copy and paste or repeat code or writing a lot of code in certain places let's say you're writing out a business role okay and i take a business rule and i am going to bring up studio with my good old classic community live stream application and i've got a test in here i'm pulling up a random business rule i didn't even look at these before the show started but i've got the advanced checkbox checked here the advanced tab is on and ooh this is a tough one okay your goal should be to get as much code out of your business rules out of your script includes out of your workflow actions and into script includes that is your goal okay it makes it easier to build applications and test applications because now you're dealing with very small tight functions very specialized things that accept one two three inputs whatever it happens to be and returns a specific result you're not trying to trigger a business rule or walk through a workflow or do something that may take 20 minutes just to get to the point where you need to test it and if it fails you've got to do that test again putting it in a script include allows you to test it very quickly unit test it test it on a specific point of interest let me see if i've got a better one in here uh populate the g scratch pad for demo i may not have one in this particular application but here's oh i was this was called demo i was working on some artwork for an upcoming podcast we do have a developer podcast coming up that reminds me i don't need that script anymore uh let's go be our test on cls test let's populate the g scratch pad this one i don't think has much of advanced in it yeah so nothing really appetizing here but i maybe i have one in the ui action i don't know create default tasks ah this one i know does because i was just looking at the script include that it calls so here great example of how to get nice and tight code yeah i may only use this code in one place that's fine think about your script includes as just reusable components but they could be only reused once that's that makes it easy to test because i can go call this copy templates with a glide record parameter and say go make some template tasks for me i could put that in a ui action i could put in a business rule i could put in a flow i could i could put it wherever i want to create this these template tasks related tasks to a parent record over and over and over again and i know that function will work and if i have to change the api i really only change it in one place talking to david liu he has the david lu that's in the demo data the david liu who founded servicenow with fred luddy that you see his name all over the place it's a real person dr david liu he told me about some of the early days in servicenow fred had a law this wasn't this wasn't just guidance it was a law it said if you are copying and pasting code say from a business rule to ui action frankly you're doing it wrong you're not observing object oriented programming because now if there's a bug you've just made two bugs and you have to go track them down twice if you are using a library of centralized code a script include you can fix it once and know that it's going to be fixed if you need to change it or you need to parameterize it or you you you're doing that in one central place and then you can go find where it's being called much easier script includes are hugely valuable so if i haven't beaten that into your head yet you've got you've got more time if you'd like go reference episode 26 excuse me episode six of tech now andrew kincaid and i did this years ago 2013 i think it was so about seven years ago still holds up we walk through different ways to build script includes i'm going to do a recap of that very shortly instead of that whole hour episode i'm going to walk you through the different ways you can build them and why you would want to use certain ones so many of us are familiar with building a script include from scratch i'm going to do this through studio you can do wherever you like i'm in a scoped app you can use it in global doesn't matter and under here i'll click twice give it a name let's call it cls let's call it demo because i'm already in the cls app and because it's a scoped app it prefaces this so even if i had another script include called demo in another scope i wouldn't collide notice that it gives me this template this is a default value when you type in the name it says let's do a class create there's there's two main things in here one is the class create and the other is this prototype when you see this prototype i'm going to be writing a json notation for these functions so i can call my function is defined as a function and i'll pass it a string give it a parameter and i must have a comma down here i am separating these blocks of the json object with commas if you don't it'll give you the big red mark and it says hey what is this i don't understand token type that just says you forgot your comma so in here i'm going to do a return hello plus a string a very simple function but you get the idea it is not how can i say this it is not a real function this is a blueprint when you create a prototype it's like a blueprint and a house from the blueprint i can make multiple identical houses it's a plan that's what a prototype is in order to use this i will save it and i will go to my script background and say i am in the demo app blow that up just a little bit for you say new demo my function chuck pass it a string i must instantiate it i must make a an object out of that prototype i'm going to build a house based on the blueprint if you want to think of it that way i could save that to a variable first many of you have seen this method where it says bar new demo and then you call a function something like x dot my function we did this with the array utils just the other day i think that was last monday and if i run that it should say it will return a value so i want to capture that value that would be nice right hello equals and then i can print it out gs.info hello run that and i will get hello chuck because i passed in chuck the function did its thing returned a result the key is when you have a prototype you need to instantiate it whether or not you choose to do it in two lines or one line or if it works that way when you instantiate it the value to having an instantiatable script include probably may have noticed it automatically put in this initialize function that's a run once when i say var x equals new demo it runs whatever code is in here i can set up things that may be global to this object and once x is set up and instantiated kind of like hey i'm going to build you a house and it's going to come furnished okay this is where i specify what the furnishings are what the appliances are they come with your with your house this is a way to set things up once but hey after 10 years the house is still there the appliances may have changed but they're not the originals so you can set things up and you reference them as this object so that's a self reference to this you say this name equals this message equals hello so i could start out with this message and use that multiple times in here to return this dot message i can reference it down here so very easy stuff to do if i wanted to change this message or refer to it the reason i mention that is because originally i was putting in like this task table equals xc 66238 cls 2 3 2 3 2 3 okay task and that name was kind of like a constant it was known throughout the scope of that x object it could refer to it internally this is a very common practice if you're doing script includes and javascript programming is referring to something throughout this the scope of that variable the problem was it wasn't known unless i instantiated it in other places so i'd have to keep saying new demo new demo new demo new demo to get that table name didn't quite do what i wanted found a better way there is another way and you may have seen some of these there is a way to create a script include without the prototype ah you may have seen this or you may have seen the notation used and not understood exactly what it is by saying class create then i say demo dot and some function maybe let's do uh demo.hello equals function pass up my parameter and return same kind of thing hello plus string now the usage on this i believe i need that so it's happy if i got that right not sure if my syntax is exactly right today the difference is i don't do a new there's no initialize but the cool thing is i also don't use the parenthesis notation you can say demo dot my function pass it chuck and you may have seen function calls like this uh my function is not an object what did i call it did i not do it right no i'll call that hello well let's change that when it didn't go right change the name go back here run it hello is not defined okay oh because i didn't save it i saved it as x we're getting closer this is how debugging goes x run there okay little different notation on how it's called i don't instantiate it there's no initialize i'm not building the house it's sort of like having a a ready-made house on demand i need that function run it now this is a way you can group like functions together so if i've got uh maybe a grouping of functions that i don't necessarily need an object for i don't need to instantiate it i just want these at the ready user functions get a user's name get users groups get the tasks that are assigned to the user okay you get the idea i could put those together without making the whole prototype thing i normally gravitate to the prototype notation first the reason i show you this is because you can do other things besides functions you can put in of course there's a way to do this hybrid you could do the object notation or the prototype you could do a prototype and have things outside the prototype that are just those direct callables you still have the class and you can call them that way so you can do both they're very rare but i have seen those what i tend to use these for now is demo dot task table equals x underscore 66238 underscore i think that was the number yes yeah always know your instance id cls 323 task the beauty of this just like the function oh i forgot to mention the the other there was one more method that you may have seen and that is no class but just a function and if you look at let me go to my script includes script includes and i think there's one called get my items there it is it is simply a function there's no class definition there's no prototype definition it is just a straight up function and this name in the function this name must match this name in the name field this is a globally accessible function back in the days before script includes everything was about 2006 2007 we made global business rules which made functions available to anyone the problem with global business rules is they were loaded on every page for that table that they specified what's the table global so guess what you get a whole bunch of functions that are loaded that nobody ever needs could be a performance issue so don't use global business rules in fact you can't use global business rules in scoped application the global table doesn't appear in a business rule for a scoped application in global you don't need to you can do this kind of thing now don't go updating all of your old global business rules you you could if they're yours but don't go to the out of the box ones the baseline ones and start making script includes for them that'll just kind of mess things up we want to leave the servicenow baseline code to the servicenow people if you've built these in the past you could easily convert them to script includes you don't even have to change how they're called they're just called these functions it says x equals get my new items or get my items this could be used in a number of places don't need to even care where it's used if you're converting a global business rule to a script include so i wanted to show that you may see that method script includes are very very powerful and very flexible there's a number of ways to use them again the most common ways are with the prototype the class there's also this other way that i'm showing you here or here to be more exact where you can define things and then use them so if i look at my constant script include that i built for this app i typically call them constants it's like a definition section it clearly points out these are my constants and i'm not the one who came up with this idea i think goran actually brought it to my attention when he was looking at an sdlc thing and he went what is this it says sdlc dot some table name or sdlc.some value name and it is a declaration there it is you got the class create and then you put in the various values you can do tables i often put in the scope that way i can preface this with something like constants.scope let me blow that up for you a little bit more you could preface it this way and then i know the table name is employee why would i do this instead of just typing hey i need a new glide record on that well sometimes the table names are hard to remember aren't they especially when you've got a scope an app but is it you underscore is it not i don't remember but if you're creating an app such as i've got going on as a pet project and it's got 20 different tables and i can't remember what the name of some of the many to many tables was because this sticks in an underscore m2m and you've got the source table and the target it's just the it gets kind of nasty but to remember constance.score table you come up with your own style guide if you like the table or the the constant itself is uppercase it stands out a little bit better in my opinion anyway when you look at shrink back down there when you look at a ui action for example or the script include called template task that now has let's put this away that a little bigger and i can blow this out see you know what let's just i was going to copy it over to vs code but i wouldn't get the color coding let's do that a little bit better here is my class create here's my prototype and i've got a function definition in here called copy templates this is the one that we saw in the ui action right there it is the ui action is now going to be very easy to debug because i've already tested the function to copy the tasks and again if i want to put this call into a business rule or anywhere else on the server side i can do that where did my template task there it is i would not want all this code what is this about 20 lines from line 10 to 30 25 lines of code in a ui action kind of makes me go throw up a little in my throat don't do that okay that's not an effective way to write your code plus you don't have any way to call that again after it's outside the ui action now just not good so i've got this i've tested it i've even commented it a bit so maybe take that 35 25 lines down to about 20. other things i could do look i've got a property in here okay properties are great we'll talk about them another time do they go in here or am i using the same property over and over and over i could very well just go like this and say what are my default fields well here's some fields here's a property what am i going to use instead let's go to the constants say put that in there call it constants dot field property because it's not a table property equals gs get property i could put functions in here like you saw before i'd probably put very trivial functions in here maybe to concatenate something or uh you know like that might be better as a function i don't know you you decide what you want in there but keep it to the definition now instead of just being available to this one script include template task let's go with constants and notice also that it says hey i know that it's a class it makes it dark why is that important field property because when i save it which will bring it back to the little window which is kind of annoying i can right click on it and say open the definition and it brings up my constant script include which i thought was already opened over there i'm not sure why it opened a new window when it should have known there was already a window open but i get that ability to go right to that definition and go what's in there what do i need to add how many things do i need to add and on my pet project that thing's pretty long with some properties and some it's mostly table and properties is what i put in mine you decide what you want to put in yours great stuff uh scenario populate a related list of members of a signed group and no assigned incidents to them when sounds like a great community question abhishek can a script include contain private and public functions or data types as we have in other object-oriented programming languages the short answer is no javascript does not understand this private and public class what you'll often find however is a notation and this is common in many of the servicenow baseline script includes if it has if it starts with an underscore its intent is to be used only in that script include think of it as a pseudo way of saying this is private i'm going to use it privately but technically it could be called outside just by calling that so that's there is no javascript private and public not my choice just the way things go uh how many classes are defined in a script include uh one the name of the class is the name of the script include so easy answer is that constant library in global scope the one that i built is not you can see the api name is prefixed with the scope name you can do this in in global apps but i would use a very unique name like if i was going to have my incident constants i would call it incident constants because it's global you don't you can't call it constants it'll literally fit with the next person who wants to call there's constants and it would be very clear when somebody is seeing it in the scoped app it's going to say instanceconstance.tasktype instanceconstance.timeout inst you know whatever you want you would have your definitions in that constant script include other cool part about this as i mentioned with script includes is if i go down to say a scripted rest resource i can now use my constants so it doesn't matter there was another practice and you'll you may see this in certain scripts that script includes could only be used if they had a gs dot include that has gone the way of the dodo you'll still see it in some code doesn't hurt anything but i don't use it it's not needed they're brought in on demand so if you see a gs.include you can pretty much ignore it you may see this in some very old scripts i haven't seen a need to ever ever use that again since about 2008 when i started so just disregard that but what i can do is if i need to do a var gr oops let's try that again let's try that again come on chuck excuse me var gr equals new glide record i can now say constants dot task table very easy to remember and when i'm reading this it jumps out at me that this is a constant and should i need to change the table which i have done numerous times i change that definition once there's the there's the winning ticket right there is less maintenance okay i change it in the constants and all my scripts know that this went from sysunderscore user to customer let's say i extended sysuser to a customer table and now i need to reference it in a different way it's no longer referencing cis user because that doesn't include the extended fields you kind of get the idea way easier to just change it once in your constants of course you know if this is a team project or enterprise application you need to coordinate the change management with all of that and everybody's got to understand what you're changing if you're changing constants you're probably changing something pretty massive maybe maybe not you check but add them liberally change them judiciously um let's make sure i hit all of my notes the d table names property other static values limits any magic numbers that you see so for example if i've got my employee table that i am all over the place yeah you can use in the right pointing device this one should probably be a constant okay this is my demo app it's been through various iterations so it's probably not my cleanest example of code but it would make more sense to say constants.employeetable here and go back and define that in my constant script include which was over here as employee table it's already done yay good it makes things a little easier to read literally magic numbers like this a set limit hmm very good idea if you don't want to retrieve every single record or you want your script to prevent from running away you could build in now think about this think about this instead of hard coding values like this you could put them in the constants you could put the constants to call a property and now say you're in production you change a property you can now get five records or 50 records or 50 000 records so your script is the behavior of your code is now adaptable based on a property putting unit constants is a little more rigid because you still need to modify in dev get it promoted that sort of thing by building this layer of abstraction you can define what you want data driven where you want property driven what you want as constants to be globally understood across the entire system so the next question comes up is if you've got two applications that are working together and one wants to reference the constants from the other aha that's pretty easy too let me go to my script includes again and find something with the name constant in it and i believe there was one for pwd constants this is in global i need to reference it with the full api name if i tried this from scripps background my scope down here let's go down here is currently the cls app and i said var x equals pwd constants dot i don't remember what the constant was type underscore info okay i can just pull things out of there that was it right let's just type that pwd constant type underscore info we'll do a gs info on that it is going to complain and say i have no idea what pwd constants is it says it's not defined because i have now crossed that application boundary and of course you all know this from using scoped apps for a while preface it with the scope name the same would be true uh illegal access to private scope aha that's a different issue because this is available to this application only i can only do that and i probably set mine up that way too right let's go to my constants it's not uncommon to have this application only say look these are private to me you don't get to see them you you don't get to use them but let's go the reverse direction and make my constants available to other applications so if i go to global and say constance.scope or employee table or whatever it's going to say what is that well it says chuck you forgot to put on the scope name so we all do this paste that on oops too much i got the whole thing make sure i have two dots feel that's constant scope run it and it says there's your scope those default fields is not defined because i didn't do anything yet there's something wrong in my constants but i can use these anywhere on the server side very powerful stuff so in summary use script includes faster for testing and building improve reliability in your code use constants to make it easier to maintain those hard-coded values whether it's a set limit or a table name or something that may or may not change doesn't matter to me but if it does need to change you change it in one place and you it's easier to remember the constants for one thing employee underscore table way easier than x underscore 66238 underscore cls 323 underscore employee trust me when you're writing glide record queries a number of times that's no fun and i don't want to keep jumping to another screen to do a copy and paste and it makes the code a little more readable so easier to manage without the cryptic numbers and strings and pretty much any time i see something in quotes a yellow flag goes off and says i ask myself should this go into property should this go in constant should this go in cis ui message get this out of my code because it feels too rigid and i don't want rigid code use script includes of course to centralize avoid copying and paste and then you can use them in business rules and flows and you could use them to pass values to client scripts so if you do need the constant information in a client script think about maybe you've got an on load and a display business rule that calls a script that loads up your constants and says here client script they're all for you do we have other questions in here is that constant of the library scope we call that question can we define a property in json with all the constants and pull that into a script include to provide easier way to change the constant value i don't know that that would if it's if it's in a json value that you want to change then it's not constant anymore is it [Laughter] theoretically you could you could put that it is a class you could define constants that's something as json you might have to parse it i don't know if you want to store it as something parsable or not or stringifiable but excellent question would it also be possible to run a function from the constants if constants.functionname is defined yes yes it is and that's off that's when one of those cases i showed you before with the script include that contained just the class create and then it had a function down there you would call it as class dot function you don't need to instantiate it that was earlier in the presentation so if you missed it you can always go back and rewind however i am done here today join me thursday july 23rd when we talk about as he goes to his notes we are going to be talking about custom flow actions this is a technical deep dive time i'm going to show you how you can create some custom flow actions so if you want to extend again on the topic of reusability components things you can use in various flows i'm sorry we're talking yeah various flows and then next monday the 27th we'll be talking about subflows and why those are very powerful you probably want to consider using subflows before you even think about writing a flow so custom actions lots of fun these are these are like the script include of 2020 for me they're all they're very powerful and i'm writing a lot of these custom actions uh because some things aren't available out of the box and some things i want to write for my own specialized applications but they become very easy to just plug in and reuse across applications so join me monday 2 p.m up excuse me thursday the 23rd 2 p.m utc do the math wherever the time zone that is and i will see you there i invite you to participate in the community at community.servicenow.com if you aren't already thousands hundreds of thousands of really smart people on a wide variety of topics to engage with for now i'm chuck tomasi and until next time thanks again and i hope you've had a chance to learn and share and help i will talk to you again thursday [Music] thanks [Music] you

View original source

https://www.youtube.com/watch?v=B94UUQPDyDg