0% found this document useful (0 votes)
16 views20 pages

Basics of User Defined Scripting

The document provides an overview of User Defined Scripting (UDS) in MAS 90/200, focusing on its implementation, prerequisites, and differences from other scripting methods like Business Object Interface (BOI) and button scripts. It emphasizes the importance of understanding business objects and object-oriented programming concepts for effective scripting. The content serves as a foundational guide for developers and managers to identify scripting opportunities and improve client solutions.

Uploaded by

Jane Amorim
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views20 pages

Basics of User Defined Scripting

The document provides an overview of User Defined Scripting (UDS) in MAS 90/200, focusing on its implementation, prerequisites, and differences from other scripting methods like Business Object Interface (BOI) and button scripts. It emphasizes the importance of understanding business objects and object-oriented programming concepts for effective scripting. The content serves as a foundational guide for developers and managers to identify scripting opportunities and improve client solutions.

Uploaded by

Jane Amorim
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Basics of MAS 90/200 User Defined Scripting

by Alnoor Cassim, CallForHelp.biz


Contents
1 Introduction: .................................................................................................................................... 3
2 Ideal Prerequisites for 4.4 User Defined Scripts / Event Scripts ...................................................... 4
3 Acronyms / Terminology ................................................................................................................. 4
4 Business Objects and Object Oriented Programming (OOP) .......................................................... 5
4.1 Business Objects ..................................................................................................................... 5
4.2 Object Oriented Programming (OOP) design concepts:........................................................... 5
4.2.1 Inheritance........................................................................................................................ 5
4.2.2 OOP Goals Include Reusability ........................................................................................ 5
4.2.3 Difference between UI, Bus, SVC, Upd, Rpt objects ......................................................... 6
4.3 Other Applications that use the Business Objects of BF modules: ........................................... 6
4.4 How the BOI works .................................................................................................................. 6
4.5 How are 4.4 Customizer Event Scripts different than BOI? ...................................................... 6
5 How are 4.4 Event Scripts different than button scripts? ................................................................. 7
5.1 Customizer Link button is for UI scripts not Business Object scripts ........................................ 7
5.2 Script Perform Logic (SPL) on a Customizer Link Button ......................................................... 8
6 UDS Resources: ............................................................................................................................. 8
7 Is 4.4 UDS / Events Scripts the Right Solution for the Client? ......................................................... 9
8 Before Coding the Script ............................................................................................................... 10
8.1 Design your plan to accomplish the project goal .................................................................... 10
8.1.1 Consider the new Edit Field Enhancements features with UDF mapping: Auto-Total (aka
Total From) , Expressions (Add/Subtract/Min/Max), Ignore If Null, Document Multiplier ................ 11
8.2 Master Developer Hook ......................................................................................................... 12
8.3 Validation ............................................................................................................................... 12
8.4 Event Identification ................................................................................................................ 13
8.5 Good Scripting Practices: ...................................................................................................... 13
8.6 Shadow Tables (UDT): .......................................................................................................... 13
9 Implementing UDS........................................................................................................................ 14
9.1 Defining Event Scripts ........................................................................................................... 14
9.2 Variables Passed into the Scripts .......................................................................................... 14
9.3 Script Events ......................................................................................................................... 15
9.3.1 Table Event Examples: ................................................................................................... 16
9.3.2 Column Event Examples ................................................................................................ 17
9.4 UDS Specifics........................................................................................................................ 18
10 Review Sage Script BT_InitDemo.vbs ....................................................................................... 19

Basics of User Defined Scripting – Version 1.20 Page 2 of 20


Copyright © 2010 CallForHelp.biz. All rights reserved.
MAS 90 / 200 4.4 Advanced Customizer Scripting / User Defined Scripting

Today we will just touch the surface and explore the possibilities of User Defined Scripting (UDS)
introduced in Version 4.4. Putting these concepts into real world MAS 90/200 client scripting projects is
the best key to success.

This class just covers the basics. Use this as a stepping stone for further advancing your skill sets.

Depending on your role in the organization, you goal may not be to necessarily apply technical concepts
into practice but instead/also identify opportunities. Interviewing the client about their business processes,
discovering where there are bottlenecks, inefficiencies can lead you into scripting ideas that will solve or
mitigate these issues.

Please ask questions along the way. Questions that cannot be answered in class can be researched
further with the answers sent to everyone.

1 Introduction:

For the developers, programmers, and “techy types”, attempting several real-world coding projects and
viewing code samples is the most effective way to learn and produce these scripts. No single person or
company in the MAS 90 community will end up being a complete guru but over time you can become very
good at it once you have enough projects under your belt and have become accustomed to all the
nuances, quirks, and notables about the MAS business objects. All your initial scripts will take longer to
code and debug but subsequent UDS projects you engage in will have better design, flow, and faster
delivery dates to client.

Note that UDS is one type of scripting in MAS 90. There also exists Business Object Interface (BOI) and
Script Perform Logic (SPL) which is discussed later. Also the version of MAS 90 largely determines what
choices you have.

For every staff member in the MAS 90 reseller organization, reviewing the 2 Sage videos by Chief
Architect, Steve Malmgren on Sage MAS 90 v4.4 Customizer Enhancements is a great sampling of the
type of projects/solutions that are possible to implement for clients. Always be listening to the client on
their process issues, their complaints about what the system can’t do, what they wish it would do. These
lead to scripting opportunities.

For the managers, in most cases, certain people within the company will end up being the “goto people”
for scripting projects. These individuals who have a propensity towards programming and learning the
MAS business objects will end up having the best mastery of this skill set. But everyone needs to be able
to identify opportunities!

Occasional references will be made to the Sage scripting demos today. Please ask questions along the
way.

Basics of User Defined Scripting – Version 1.20 Page 3 of 20


Copyright © 2010 CallForHelp.biz. All rights reserved.
2 Ideal Prerequisites for 4.4 User Defined Scripts / Event Scripts

1. VBScript knowledge – Online course, college course, books, tutorials, etc


e.g. Online - http://www.w3schools.com/Vbscript/default.asp

2. Sage Business Object Interface (BOI) Anytime course

3. Customizer / Custom Office knowledge

3 Acronyms / Terminology

AC - Advanced Customizer - Refers to Customizer in versions 4.4 and higher.

AFS - Advanced File Scripting (aka User Defined Scripting in 4.4 and higher)

AFS - Advanced Field Settings (introduced in 4.20, enhanced in 4.40 ). Allows you to do the following on
Standard MAS fields for BF modules:

• Force UpperCase (depending on user/company combination)


• Make the field Required (depending on user/company combination)
• Set a Default Value
• Assign validation (Range, List, UDT)

Example: Let's check out Promise Date and AliasItemNo from SO Invoice Detail as an example.

Common Request: In Customer Maintenance can the Residential checkbox be a required field and
defaulted to Yes? The answer is Yes and you don’t even need any kind of scripting.

Note: Having said all that you can enforce all the above with far greater control if you use AFS/UDS
scripts instead in 4.4.

BF – Business Framework

BOI - Business Object Interface (external COM interface to support access to MAS business objects).
Find examples of BOI apps and discussion on Sage MAS Community Forums.
http://community.sagemas.com/t5/Business-Object-Interface/bd-p/MAS90AND200BOI

UDF – User Defined Field

UDT - User Defined Table

UDS – User Defined Scripts aka Event Scripts

 Ability to change the behavior of the business objects by scripting customer specific business
rules which get executed automatically on predefined events.
 Because it is done at the business object layer, these rules are enforced from Sage MAS 90
Entry Screens, VI Imports, COM Access and new Web Services.

Basics of User Defined Scripting – Version 1.20 Page 4 of 20


Copyright © 2010 CallForHelp.biz. All rights reserved.
VBSCRIPT – Refers to Visual Basic Script: A scripting interface that uses the Windows Scripting Host
(WSH). Note: It is not installed on Windows 2000 (Server or Professional) by default and after installing
the WSH on it, not all WSH functions are available (e.g. using Open File Dialog to allow user to select a
file).

VBS unlike VB.Net, Java, etc., is not a typed language but rather a scripting interface using the WSH.
Scripts are far less structured, don’t have as many requirements. There exists plentiful information but if
you don’t use good and consistent coding practices, you can “step on your own foot”.

4 Business Objects and Object Oriented Programming (OOP)

4.1 Business Objects

Application logic created to follow a set of business rules. It has methods (functions) and
properties, some of which are internal/private/protected and others that are external/public

An object is instantiated from a class (.pvc, .dll, etc). In MAS 90/200 business objects are used on BF
modules only.

E.g. The sy_session.pvc file is just a class. Here are common ways you make an object out of this class

Set oSS = oScript.NewObject("SY_Session”) ' BOI using VBS


oSession = NEW("Sy_Session") ! pvx
oSession ' UDS - Handle to session object

4.2 Object Oriented Programming (OOP) design concepts:

Includes: Encapsulation, Abstraction, Polymorphism, Inheritance

4.2.1 Inheritance

By creating an object (e.g. AR_Salesperson_bus) you "get for free" the methods and properties in that
class and the classes it inherited. (In the pvc class file, it's the LIKE statement between the DEF CLASS
and END DEF).

AR_Salesperson_bus.pvc has:

LIKE "SY_Maint"
LIKE "CI_ARDivision_val"
LIKE "CI_SalespersonNo_val"
LIKE "CI_Country_val"
LIKE "CI_ZipCode_val

4.2.2 OOP Goals Include Reusability

We will see this through example

Basics of User Defined Scripting – Version 1.20 Page 5 of 20


Copyright © 2010 CallForHelp.biz. All rights reserved.
4.2.3 Difference between UI, Bus, SVC, Upd, Rpt objects

Type Extension Example Usage


Business _bus SO_SalesOrder_bus Create, Read, Update, Delete
SO_SalesOrderDetail_bus records. Add new lines to data entry.
User Interface _UI AR_Customer_ui Show MAS 90/200 screens
Service _svc AR_Customer_svc Read only. Some have additional
AP_Division_svc methods.
Report _rpt AR_AgedInvoiceReport_rpt Select report setting. Print, Preview,
SO_InvoicePrinting_rp Defer reports.
Update _upd SO_SalesJournal_upd Print register, recaps and process
GL_GeneralJournal_upd posting.

4.3 Other Applications that use the Business Objects of BF modules:

 Business Object Interface (BOI) – see below

 Visual Integrator – On imports for Business Framework modules, V/I is also a “client” of the MAS
business objects; that is, an import job uses the same business objects that manual entry in MAS
90/200 does. That is why creating a BF import job ends up having far less fields in the Data tab. A
legacy V/I import job does not use business objects and therefore requires a lot of perform logic.

 Web Services in 4.4

 Customizer 4.4+ UDS Scripting - As a feature it does allow a fair amount of UI control.

4.4 How the BOI works

BOI is a programmatic interface (API) to “use” any Sage MAS 90 / 200 object. The interface allows any
programming language that supports COM to interact with MAS 90 / 200 objects such as C#, VB.Net,
VBScript, etc. As Steve Malmgren says if you can do it with V/I it can be done with BOI.

Note: Although Business Objects are available to these external applications only the public methods
(functions) and public properties are available not the private/local ones (e.g. Credit Card Number
decryption is a private method and not exposed to the BOI).

When did it come about? 4.00 with the General Ledger


Can you use it for all modules? No only BF modules not legacy modules
Can you use it to write back data into MAS? Yes

4.5 How are 4.4 Customizer Event Scripts different than BOI?

BOI is completely external and does not run within the context of Customizer. Therefore when coding it
manually requires obtaining the session object (oSession) and you do not “get for free” all the other
automatically passed in object handles (oBusObj, oScript, oHeaderObj) and the 2 column events (known
as “column” and “value”) that come with UDS. Also UDS allows some amount of UI logic through the

Basics of User Defined Scripting – Version 1.20 Page 6 of 20


Copyright © 2010 CallForHelp.biz. All rights reserved.
oUIObj handle. BOI has a fundamental purpose in design for external applications to read/write data via
the Business Objects similar to V/I.

5 How are 4.4 Event Scripts different than button scripts?

5.1 Customizer Link button is for UI scripts not Business Object scripts

The traditional button script involves customizing a panel by creating what’s called a link button (e.g.
BT_LINK_1) and then attaching a script to the button. To run the script, the user must click the link button
in the panel. In other words, the script cannot fire via any other event, such as entering through a field,
clicking on a panel tab, when loading a record on the screen (e.g. selecting an order in S/O Entry), etc.

Also the button script runs at the UI level, not at the business object level. This is not a bad thing at all as
you can do things such as can read/write to standard fields on the screen, UDFs on the screen, run MS
script code (VBScript, Jscript) to execute practically anything supported by the Windows Scripting Host.

Example 1a – Button Script: In S/O Invoice Data Entry on the Lines tab, you have created a line UDF that will store
the Inventory Account No of the Item Code. The problem is this piece of data is not on the list of variables available
for the script. Via button script you can create an ODBC or OLEDB connection (e.g. SOTAMAS90) to the
IM_ProductLine table to lookup the product line, find the Inventory Account Key, then via ODBC / OLEDB connect to
GL_Account table to find the fully formatted Inventory Account No. When you click the button, it will populate the UDF
for that line but now you must press the button for each line on the invoice.

Note: Via the WSH you can connect to MAS tables you need, to Access databases, Excel spreadsheets, Outlook
contacts, SQL Server databases, and other miscellaneous tasks supported by the WSH.
st
Example 1b – Event Script: You can position yourself at the 1 line, then start a loop to traverse from Line 1 to the
last line. For each line in the loop, you will connect to IM_ProductLine_bus to lookup the product line, then find the
Account Key, then connect to GL_Account_bus to lookup the Account Key and find the Account No, then set the
value of the Account No into the line UDF, then write the line.

Example 2a – Button Script: Create the link button and script in S/O Entry and name it “Accept” and place it in the
Totals tab in the location of the real Accept button. Also move the real Accept button to another place on the panel
and resize it to make it small enough to be not visible. When the user clicks Accepts on the order, s/he will really be
running the scripted Accept button. Goal 1 is take the UserCreatedKey and via ODBC do a lookup against Sy_User
table. The find the UserLogon field and store the value into a S/O Header UDF. Goal 2 is in the last line of the script
which will execute the SendKeys() function of the WSH as a way of automatically pressing the keyboard shortcut of
the real Accept button. The advantage is the user had to press only 1 actual button. The disadvantages are
SendKeys() would require the script to be executed on the client and also on Vista and Windows 7, SendKeys() is no
longer supported.
st
Example 2b – Event Script: 1 goal has to be accomplished the same way because the Sy_User table is not a data
nd
source of SO_Invoice_bus unfortunately. If it was, then no ODBC connection required. But 2 goal can be
accomplished by using what’s called the InvokeButton() method of the oUIObj object. This allows us to click a screen
control like a button or folder tab.

Example 3a – Button Script: A UDF on an S/O Entry line needs to be populated with the result of a calculation
involving Qty Ordered multiplied by a value from an Excel spreadsheet. You must press the button for each line.

Example 3b – Event Script: Use the Post-Validate column event for Qty Ordered field. Once you enter the Qty
Ordered, the script fires. You can take it another step and store the Excel data into a UDT and look up the data faster.
Basics of User Defined Scripting – Version 1.20 Page 7 of 20
Copyright © 2010 CallForHelp.biz. All rights reserved.
For cases where a button is required (e.g. client is on Version 4.3), you can overcome some of the button
script limitations if you use Script Perform Logic (SPL) instead of MS Script – see below.

5.2 Script Perform Logic (SPL) on a Customizer Link Button


SPL gives you access to more business objects since as you are using ProvideX directly. As a result it
can accomplish some tasks not possible with the UI script capability with the MS Script option in
Customizer Selection (VBScript and Jscript). Often it is used in data entry screens to gain access to
variables on the Header, which is something is not possible with VBScript and Jscript.
E.g. Your Sales Order has 10 lines with varying amounts for QuantityOrdered. You want to add up the
QuantityOrdered column and store the total in a header UDF.

• SPL work like this:


Your Customizer Link button uses VBScript. The script will have 1 line only:
MAS_SCR_PFM = "<relative path and name of a providex program>"

• This makes many 4.3 scripting projects possible that you thought were not possible. However it's
certainly nothing close to 4.4 UDS. Here’s an example that adds up the Quantity Ordered values for
each line in the Lines tab of Sales Order Entry and then stores the value in a header UDF.

coHeader'Lines'MoveFirst()
WHILE NOT(coHeader'Lines'EOF)
coHeader'Lines'GetValue("ItemType$", tmpItemType$)
IF tmpItemType$="1" and ProductLine$ < "6000" {
coHeader'Lines'GetValue("QuantityOrdered", tmpQuantityOrdered)
UDFValue += tmpQuantityOrdered
}
coHeader'Lines'MoveNext()
WEND
coHeader'SetValue("UDF_TOTAL_QTY ", UDFValue)
UDFValue=0 ! In case Update Total Qty button is pressed again
RETURN

• Slade Hornick offered examples on the old SageTalk forum


• In 4.4 not only can this type this of script be accomplished through UDS via VBScript but it can also
be done strictly with Customizer alone just using User Defined Field and Table Maintenance. One of
the new Edit Field Enhancements features is the Auto-Total / Total From feature which allows you to
total up any numeric column on a line entry grid and store it into a UDF.

6 UDS Resources:
• ObjectReference.chm (Help folder)
• FileLayouts.chm (Help folder and Resources menu on Business Desktop)
• Scripting.doc (found in \mas90\CM\Script folder and Sage MAS Community forums)
• MAS console window (File / Run / SYZCON or run pvxwin32.exe in \mas90\home)
• Text Editor (e.g. UltraEdit)
• VBScript resources on internet and other places
• A 4.40 MAS 90 installation using ABC demo data and UDSDemo.m4x imported. Run the
InitDemo script found in Item, Customer, and Vendor Maintenance. These will refresh shadow
tables for Inventory, Customers, and Vendors.
• Sage videos -
1) Demo only -
Basics of User Defined Scripting – Version 1.20 Page 8 of 20
Copyright © 2010 CallForHelp.biz. All rights reserved.
Sage MAS 90 v4.4 Customizer Enhancements

http://sage.edgeboss.net/wmedia/sage/mas/sales/v44customizer.wvx

2) Fewer demos but with script code explained

Next Generation of Customizations for Sage MAS 90 (MD specific information edited out)
http://sage.edgeboss.net/wmedia/sage/mas/sales/nextgencustomizations.wvx

• Sage MAS Commmunity Forums - Steve is responding to scripting questions and providing some
examples
• Customizer Reports
• Customizer Export Wizard - Design your UDFs, UDTs, screen/panel changes, and event scripts
on your computer, then export to .M4X file.
• Customizer Import Wizard - Import your .M4X file on the client's system:

Hints:
1. Make a FULL back of \mas90 folder on client's system before importing the .M4X file

2. Prior to project start, for complicated projects, if possible get a copy of client's \mas90 folder and put on
your system. Alternatively, remote into client's system, use Copy Company to make a copy of the
company that will run the UDS. Then turn off Allow External Access in Company Maintenance for the
main company and when making the screen/panel changes, create them for the test company only (e.g.
###-TST, instead of ###-###)

7 Is 4.4 UDS / Events Scripts the Right Solution for the Client?
Before you decide on Customizer scripting as the solution, consider the following:

• What is big picture goal for client?

• What is the client's budget?

• Is there another way to do it?


o Traditional enhancement / mod
o 4.4 Extended Solution replacement from certified Gold ES Dev Partner

• What is the realistic time table and cost for the client and for yourself? Developer mods or
replacement ES:
o May be cheaper since the development cost is spread out amongst several users
o May already available to implement and will probably have more features and
functionality.
o Can be placed into an installer for installation and deployment whereas scripts cannot
because they are defined under the context of Customizer.
 You can deploy scripts via the Customizer Export Wizard and Import Wizard but
be careful. You can instead work while “remoted in” to client’s system
 Rarely can any script designed for 1 client be dropped into another client's
system and be expected to run instantly.

Basics of User Defined Scripting – Version 1.20 Page 9 of 20


Copyright © 2010 CallForHelp.biz. All rights reserved.
• Consider Scripting Disadvantages:
o Although scripts can survive upgrades, sometimes not all parts of it survive
o Although scripts can replace some Extended Solutions, it can’t replace them all. Scripting
has limitations

• Responding to client requests for pricing on scripting projects can itself be challenging.
o Half the battle is in defining the scope / the specification (“spec”) properly and dealing
with “scope creep”. Anecdotally, to date, most UDS projects of higher than medium size
are more expensive for the client than a traditional “mod”, including replacement
Extended Solutions of that size.

o The other half of the battle is coming up with a reasonable estimate in a reasonable
period of time. In many cases you have to code 25 – 50% of the project just to see if it is
even possible to accomplish with UDS (unless you have read that it could on Sage MAS
Community forums or elsewhere) because the limitations are not clear at all. When
receiving a pricing request for a UDS project:

 Request more information, more detail.


 Make phone calls to the prospects to clarify the detail. This can be immensely
helpful as you could discover for example, the size and scope is much smaller
than what was indicated by email.
 Consider offering separate Maintenance and Support (M&S) to avoid “getting
burned” or make it abundantly clear in the spec what the project accomplishes
and what is not (but then be prepared).
 AVOID PRICE SHOPPERS unless you are very confident about quoting the
request. Don’t waste time researching the quote if the client has a preconceived
notion about pricing, whether they are price shopping, if it exceeds their budget.

8 Before Coding the Script

8.1 Design your plan to accomplish the project goal

• What UDFs and UDTs and standard fields will you need?
• Make Schema changes first. YOU MUST HAVE THE SCHEMA in place before you do any
scripting
• Identify which events need a script. Write it down on paper, make a Visio diagram, model as
necessary
• Research if you need to map/source the UDFs from data entry through history tables

Basics of User Defined Scripting – Version 1.20 Page 10 of 20


Copyright © 2010 CallForHelp.biz. All rights reserved.
8.1.1 Consider the new Edit Field Enhancements features with UDF mapping: Auto-
Total (aka Total From) , Expressions (Add/Subtract/Min/Max), Ignore If Null,
Document Multiplier

o Creating an Auto-total / Total From UDF for the Pre-Totals event


(e.g. Total CRV Ext Amt, Total Referral Amt)

o For Update tasks, the Add/Subtract expressions useful for incrementing a UDF in
Customer Sales History or similar. It is used for numeric columns. Min, Max expressions
are used for both numeric and date columns.
o Document Multiplier – Use with Add expression for handling credit memos and other
numeric values that need to be backed out. Allow you to create a negative value in the
script by multiplying by -1

Example: When updating UDF_REFERRAL_AMT into AR_CustomerSalesHistory, it is


setup to use the Add expression. The problem with this is a credit memo will also
increment the Referral Amount instead of decrementing it. But by checking document
multiplier you can multiply by -1 in the script when you identify InvoiceType = CM.

Basics of User Defined Scripting – Version 1.20 Page 11 of 20


Copyright © 2010 CallForHelp.biz. All rights reserved.
• Ignore if Null or Zero – Disallow overwriting a UDF default value if it’s sourced value is Null
(for string) and Zero (for numeric).

Example: AR Customer table has a manual UDF called ROUTING and is also mapped into
SO Sales Order Header where it is set up with a default value of PENDING. At the time the
customer is selected in the Sales Order Entry, the value for routing in Customer Master
comes over and will overwrite PENDING. But what if for certain customers the ROUTING
UDF is blank. It will overwrite PENDING in S/O Entry with blank/null also unless the Ignore If
Null or Zero is selected in the SO Sales Order Header UDF. If ROUTING was a numeric UDF
it would prevent overwriting with a 0.

8.2 Master Developer Hook


o In 4.4 there is a new table related to sourcing called Sy_ContextAFM
o Edit the sourcing record to add custom fields to the expression

8.3 Validation
o Will you need to do validation against UDFs? If so, you can do either:
 Range validation - Uncommon
 List validation - Common but limited to what the screen library allows (the
.M4L / .LIB file)
 UDT validation – Gaining popularity and theoretically unlimited.
Requirements include:
1. The UDT key column length must be same as the UDF length.
2. Must be defined as Multi-Line control if you want a lookup on your
UDF
 Directly in the script validation – Makes sense if validation list is small and
never changes.

o Can a UDF be validated against a standard table – NO but maybe in the future. In
the meantime use the workaround of creating and maintaining a UDT Shadow Table
(e.g. Customer Shadow UDT would have shadow of customer numbers from
AR_Customer.

Basics of User Defined Scripting – Version 1.20 Page 12 of 20


Copyright © 2010 CallForHelp.biz. All rights reserved.
To maintain the shadow table, you need scripts in the Post-Write and Post-Delete
events (at least). For creating and refreshing the shadow table, you need a “Shadow
Initialize” button script just like in the Sage demo.

o Will you need to do validation against Standard fields? If so, options are:
 Advanced Field Settings - Can do list validation and UDT validation. Length
of standard field must be the same as the key length of the UDT key field.
Also standard field must be multi-line if you want a UDT lookup.
 Creating/maintaining a shadow table (UDT). Use script to maintain the
shadow table.
 If validation is light, put it directly as a literal in the script.

8.4 Event Identification


• When does your script need to fire off - when you click Totals, when the QunatityOrdered is
entered, when a record is loaded in a screen, when a button is pressed (it is still okay to have
buttons). This will help you figure out what events you will need.

8.5 Good Scripting Practices:


• Come up with a naming convention
• Scripts default to CM\Script folder but you may want to create subfolders by client name or
project code
• Put ample comments in your scripts so you can remember later if you have to revisit it should
requirements change or you need to debug
• Test it with client's actual data before you send it to Production. You may see errors or error
causing conditions (e.g. dirty data) that you weren't expecting.
• Add error handling such as setting LastErrorMsg or WriteLog() if retVal = 0
• If client is on MAS 200 instead of MAS 90, test in MAS 200 environment (e.g. you may have
used VB MsgBox() function instead of the UI object message box)
• Turn on Debugging:
o Edit SOTA.INI and add Debug=1 to [Config] section. If MAS 200, edit the client-side
SOTA.INI
o Use oScript.DebugPrint(text) to show oBusObj.LastErrorMsg, values of variables,
etc
• Use indentation in your code so you can more easily see logical blocks (e.g. IF / END IF)
• You can use an external script editor such as pressing Notepad button (assuming bug is
fixed). But you still need to compile the master script for the business object.

8.6 Shadow Tables (UDT):


• Shadow Tables are UDTs that are essentially copies of masterfiles, at least the key columns.
You can't validate a UDF against against a standard MAS table so creating shadow tables is
a workaround for that.
• Need to a way to create it for first time use and a way to refresh it.

Basics of User Defined Scripting – Version 1.20 Page 13 of 20


Copyright © 2010 CallForHelp.biz. All rights reserved.
• Use Post-Write and Post-Delete events to insert a row or delete a row from the shadow so it's
in sync with the master. There are points in time where it still may get out of sync so consider
having a “Refresh” script to complete rewrite the shadow table.

9 Implementing UDS

9.1 Defining Event Scripts


• VBScript only
• Defined in either User-Defined Script Maintenance or on-the-fly from User-Defined Field and Table
Maintenance. These will contain code for the specific event to which they will be attached.
• Attached to one of the pre-defined events in User-Defined Field and Table Maintenance.
• A single event script can be attached to multiple business objects.
e.g. pre_validate_gl_account script could be attached to the AccountKeyPreValidate event for GL
General Journal as well as Transaction Journal
• A priority level can be assigned if there are multiple scripts to be run for the same event if the order
is significant.

9.2 Variables Passed into the Scripts

Handles to currently running objects.


oBusObj – current business object (e.g. AR_Customer_bus)
oSession – current session object
oScript – script helper object
oHeaderObj – available only if current object (oBusObj) is a detail object (e.g. If oBusObj =
SO_SalesOrderDetail_bus, oHeaderObj will be SO_SalesOrder_bus)
oUIObj – only available from within a data entry screen
For the 2 column events Pre-Validate and Post-Validate
Column – name of column being validated
Value – contains the value that the user typed in

Basics of User Defined Scripting – Version 1.20 Page 14 of 20


Copyright © 2010 CallForHelp.biz. All rights reserved.
9.3 Script Events

Event Type Script Executes…

Script-Initialization Table Runs once per business object on first script run

Set-Default-Values Table When defaults are set for a new record in the business object
Before a record is written. Can be used to fail the Write() to disk

Invoked when you run the Write() method in your script but runs
before the actual Write() method runs in the business object. Its
Pre-Write Table purpose is additional "validation". The Pre-Write lets you fail a Write.
Note: A version of Pre-Write (not the script event) is used both in
standard code and optionally in developer code. However the script
Pre-Write runs before any standard code Pre-Write or MD Pre-Write
occurs
After a record is written
Post-Write Table
Example: Maintain a Vendor shadow table after Accept pressed in
Vendor Maintenance to add a new vendor record
Pre-Delete Table Before a record is deleted. Can be used to fail the Delete
After a record is deleted
Post-Delete Table
Example: Maintain a shadow table
After a record is read

Runs after a record is put into an Edit state (1 or 2). Edit State 1
means an existing record and Edit State 2 means a new record. The
Post-Read Table
Post-Read is most commonly used for existing records such as when
retrieving an existing record from lookup or browsing to it.

Pre-Totals Table Line Entry only, before totals are calculated

Pre-Validate Column After dictionary validation, prior to Sage/Master Developer

Post-Validate Column After the column value has been validated

Basics of User Defined Scripting – Version 1.20 Page 15 of 20


Copyright © 2010 CallForHelp.biz. All rights reserved.
9.3.1 Table Event Examples:

1. Post-Read
a. In I/M, after selecting an item in Item Maintenance, disable the Cost Details tab in Item
Maintenance depending on the role you belong to. Let’s do this together

IF Not(cBool(oSession.AsObject(oSession.Security).IsMember("AllowedToSeeCostsRole")))
Then
retVal = oScript.InvokeButton("fldr.pMain")
retVal = oScript.SetUIControl("fldr.PCOSTDTL","DISABLE")
END If

b. In S/O Entry, select an order and immediately show a message to salesperson to take
some kind of action depending on order total, customer, the salesperson on the order,
other variables.

c. In Customer Maintenance, disable the Summary and History tabs depending on the
Salesperson No for the customer. Let’s do this together.

d. When loading an order in S/O Entry, set a storage variable (akin to a global variable) to
store off the OrderType. Later in Column - Post-Validate event for OrderType, retrieve the
storage/global variable to see what the original Order Type was.

oScript.SetStorageVar
oScript.GetStorageVar

2. Set Default Values - When defaults are set for a new record
Examples:
a. By default in Item Maintenance, default Product Type is Finished Good and default
Valuation is Standard Cost. However you really need it to default it to Raw Material and
FIFO. Now you can by using Set Default Values event. Let’s do this together.

3. Pre-Totals - Set on a Header bus object. Only applies to bus objects with a Header/Lines
relationship. Runs when you click on the Totals tab (e.g. S/O Entry).
Examples:
a. Add a coupon code as a misc charge line if order amount exceeds a certain value.
Remove the coupon code if order later modified to go below minimum coupon order
amount.

Basics of User Defined Scripting – Version 1.20 Page 16 of 20


Copyright © 2010 CallForHelp.biz. All rights reserved.
9.3.2 Column Event Examples

1. Pre-Validate (before a column is validated)


Examples:
a. Preventing an salesperson from clearing the On Hold checkbox or changing the Credit
Limit field in Customer Maintenance based on the role s/he belongs to:

IF cBool(oSession.AsObject(oSession.Security).IsMember("rolename")) Then
retVal = oScript.SetError(“Can’t touch that”)
End If

Let’s do this together. We can also try using oScript.SetWarning() to see the difference.

b. Allow action only on a new PO, not existing PO

If oBusObj.EditState <> 2 Then


retVal = oScript.SetError (“No only can do for new PO’s”)
End If
2. Post-Validate (after a column is validated)
Examples:
a. When creating a new sales order, after Order Date is set and Order Type is set to Quote,
the Expire Date is set to equal 60 days after the Order Date

b. In Vendor Maintenance you use the Sort field for entering some meaningful data for
Supplier type vendors only. If user puts data in Sort field, script can auto-click the
checkbox "Use PO Receipt of Invoice Entry for this Vendor" Let’s do this together.

Note: For Pre-Validate and Post-Validate events, there are 2 special variables that automatically get
passed into the script. The variable called column (string) contains the name of the column that is being
validated in the procedure while value (numeric) is the value typed in on that column by the user.

Note: These events scripts will also be observed by V/I imports that use the same business object. V/I is
smart enough to know that V/I needs to skip the events where you have some UI code in your script like
SetError or SetWarning.

Example: Identifying Session Object Methods and Properties:

• oSession in Scripting.doc
• Sy_session in ObjectReference
• SYZCON - Let's check it via SYZCON window in MAS 90/200.

Basics of User Defined Scripting – Version 1.20 Page 17 of 20


Copyright © 2010 CallForHelp.biz. All rights reserved.
9.4 UDS Specifics

Let’s look at the Scripting.doc found in your \mas90\cm\script folder.

The current business object - oBusObj (akin to "me" in VB.Net) is passed into the script. It is identified by
the table / column the script is tied to:

E.g. If a script is tied to QuantityOrdered column of SO_SalesOrderDetail then oBusObj is the handle to
SO_SalesOrderDetail_bus - now you can use the methods and properties of SO_SalesOrderDetail_bus.
Mostly this means manipulating the lines (AddLines(), etc). If script is tied to OrderDate column of
SO_SalesOrderHeader table then oBusObj is the handle to SO_SalesOrder_bus. Then you need to Set
oLines to access the Lines. See the File Layouts which in 4.4 included the ObjectReference.chm
(previously available in 4.3 only when taking BOI class)

Other objects passed into the script include:


oSession – session object
oScript – Script helper object
oHeaderObj - Object handle to the header object for the current detail object
oUIObj - Object handle to the currently running UI object.

Variables:

An object handle is always preceded with an "o" in script or in BOI


retVal or tmpRetVal or any convenient numeric variable you like is used to hold a 0 (failed) or 1 (success)
on a procedure call

Common Methods and Properties

SetKey(strKey) - set the primary key into the bus object - used to create a New record (edit state 2) or
modify existing one (edit state 1). For multi-part keys do a SetKeyValue() on each key column then
SetKey() with no arguments.

SetKeyValue("keyColumn$", strKey) - do this for every key column in a multi-part key

CopyFrom(key) - After doing a SetKey() you can copy an entire record into the new SetKey() record

GetValue() - Get the value of a column from a bus object

SetValue() - Sets a new value for a column into a business object. It does NOT write the value into the
table. It's the step before the Write(). A SetValue() can have 3 values:
0 = Fail
1 = Success
-1 = Warning.

One reason for failing is using a ReadOnly column. Another reason is failed validation. SetValue() will use
the SVC object to check validation

Write() - Write to the table - record was in memory (dirty) and uncommitted to disk before this. Use this for
doing Writes to UDTs and line records for data entry screens. But avoid doing it on the Header tab of
Data Entry screen or in a Maintenance screen as the normal Accept button will do this. In these

Basics of User Defined Scripting – Version 1.20 Page 18 of 20


Copyright © 2010 CallForHelp.biz. All rights reserved.
scenarios, oBusObj is handle to the non-Line business object. Regardless of this, definitely do a
SetValue() on both Lines and Header.

EOF - Property representing End of File. Usually used as a loop condition and in script we have to
convert to boolean using VB CBool() function

SetBrowseFilter(string) - prefilters the MoveNext() and other moves; will skip keys not meeting this
criteria.

Recordset Navigation
MoveFirst()
MoveLast()
MoveNext()
MovePrevious()

NOTES:
• If oBusObj.SecurityAccess = 0 'Inquiry access only
• After inserting new lines in an order ( AddLine(), SetValue(), Write() ), check for retVal=1
• Turn on External Access in Company Maintenance. Uncheck if you don’t want script to run in a
particular company.
• The : is a way in VBS to allow multiple statements on 1 line
tmpDiv = "" : tmpCust = ""
• Role based scripting is possible using IsMember() in session object
• Use SetError() and SetWarning() on any of the Pre events
• oUIObj – Can be used to auto-click a button or tab folder via InvokeButton()
• retVal = oScript.DebugPrint(string)
o Set Debug=1 in SOTA.INI and open Trace Window with Suppress option enabled. If MAS
200 set in client-side SOTA.INI
o You can see which events are being called as trace is running
o You can check the values of your variables

10 Review Sage Script BT_InitDemo.vbs


Let's review the BT_InitDemo.vbs to see how the ABC data for the demo is set up. Have the Scripting.doc file handy.

The following examples are done through script:

– Create new Product Lines and Item Codes, both using CopyFrom() method
– Create new UDT records using CM_UDTMaint_bus object
– Uses IM_Transaction_bus to create a receipt transaction and adds lines for all the new Item Codes
– Uses IM_TransactionRegister_upd to print the register to Deferred printing, and runs the update
– Comments throughout code explaining different methods

When looking at a script first try to understand the goal / objective of the code before drilling down too deep into the
code

set otmpBus = oSession.AsObject(oSession.GetObject("CI_ItemCode_bus"))

Think of the main screen where this object is used if you were to manually enter the data. In this case, inventory
items are added in Inventory Maintenance so the main business object is CI_ItemCode_bus. Although we have
oBusObj and other handles we do not have one to CI_ItemCode_bus. However, we can accomplish that by using
GetObject(). The above should be separated into 2 separate lines as seen in Scripting.doc and in the Sage demos.
Basics of User Defined Scripting – Version 1.20 Page 19 of 20
Copyright © 2010 CallForHelp.biz. All rights reserved.
What is the bus object for entering a new product line? (Where do I go to create a new product line?)
IM_ProductLine_bus

How do we know that was the name?


Look at the business object list in Help and use Windows Explorer.

How to script it?


SET otmpBus = oSession.AsObject(oSession.GetObject("IM_ProductLine_bus"))
Now we have access to this object and can run methods and properties on it. We didn’t have to use “otmpBus” that
was just done out of convenience. You can use oProdLineBus for example.

What is the business object for entering a new product line? (Where do you go to create a new warehouse)
IM_Warehouse_bus

How to script it?


Set oWhseBus = oSession.AsObject(oSession.GetObject("IM_Warehouse_bus"))

How to get object handle to Lines business object if Header is the main object
Set oLines = otmpBus.AsObject(otmpBus.Lines)
OR
Set oLines = oBusObj.AsObject(oBusObj.Lines)

Other Useful Line Entry methods:


retVal = oLines.AddLine() ' establish empty line - this will auto assign the LineKey and LineSequenceNo
retVal = oLines.SetValue("ItemCode$", "COKE") ' String columns must have the $ on SetValue() and GetValue()
retVal = oLines.SetValue("TransactionQty", 288) ' Even num columns are quotes in SetValue() and GetValue()
retVal = oLines.Write() ' Continue this for all lines to be written – this will write the Line

Write() on Header Considerations:


retVal = oBusObj.Write() ' This will write the Header.

Normally you don’t Write() on the header because it changes the EditState – it’s better to let the system do it when
user clicks Accept. Since there is no UI in BT_InitDemo.vbs okay to Write() on the header.

Basics of User Defined Scripting – Version 1.20 Page 20 of 20


Copyright © 2010 CallForHelp.biz. All rights reserved.

You might also like