Showing posts with label escript. Show all posts
Showing posts with label escript. Show all posts

05 February 2011

Siebel: Prototype in eScript - Part 3

In earlier posts, we have seen using prototypes to extend OOB objects. In other posts we have also dealt with user defined objects and scripts libraries. Time for seeing all three in action you say? And I hear you, we shall see how user defined object can be prototyped, and used across the application.
Problem: I need a function to lookup the description of a LOV provided its type and value
Solution: We address the problem in two steps:
  1. Define a user object and make sure it is available for the session. One of the common ways of doing this is in Application object
  2. Use the custom object to define a prototype for useful function(s) - in our case 'LookupDesc'
 Now, the how..
  • Define a variable in the application script, for example: Siebel Life Sciences
[Application: Siebel Life Sciences, (declarations)]
var MyApp;
And, call a business service where MyApp is initialized. This is just to keep the application object, it works just fine within the application itself.
[Application: Siebel Life Sciences, Method: Application_Start]
function Application_Start (CommandLine)
{
 var bsStarter = TheApplication().GetService("COG Test Proto");
 bsStarter.Init();
}

  • Write the custom business service 'COG Test Proto'
[Service: COG Test Proto, Method: Init]
 function Init ()
 {
    TheApplication().MyApp = new MyAppFun;
    MyAppFun.prototype.LookupDesc = LookupDescFun;
 }

[Service: COG Test Proto, Method: MyAppFun]

       function MyAppFun()
       {
 // this is a dummy, but funny function.
       }


  [Service: COG Test Proto, Method: MyAppFun]
function LookupDescFun (Type, Value)
 {
 try {
  var sDesc = "";
  var boLOV = TheApplication().GetBusObject("List Of Values");
  var bcLOV = boLOV.GetBusComp("List Of Values");
  with (bcLOV) {
     ClearToQuery();
     SetViewMode(AllView);
     ActivateField("Description");
     SetSearchExpr("[Type]='" + Type + "' AND [Value] = '" + Value + "'");
     ExecuteQuery(ForwardOnly);
     if (FirstRecord()) sDesc = GetFieldValue("Description");
  } //with
  return(sDesc);
 }
 catch(e) {
  throw(e);
 }
 finally {
  bcLOV = null;
  boLOV = null;
 }
 }


 That's about it, now MyApp is ready to have some fun. Again, a quick service to test how things work.

[Service: COG Test Proto Call, Method: Service_PreInvokeMethod]
 function Service_PreInvokeMethod (MethodName, Inputs, Outputs)
 {
    Outputs.SetProperty("out", TheApplication().MyApp.LookupDesc("blah", "blah"));
 }

A bit of theory on how it works:
  1. MyApp is defined as a variable in Application, the same is initialized in a business service. It does not matter what the function [MyAppFun] contains, we will not be using that anyway
  2. The prototype LookupDesc is defined as an extension of MyAppFun. Any object based on MyAppFun will have access to the LookupDesc functionality
  3. We invoke LookupDesc as an extension of the variable in the application object. There are other blogs out there who just use TheApplication = MyApp, but that practice is not encouraged as I understand
  4. When TheApplication().MyApp.LookupDesc is invoked, Siebel will look for the LookupDesc function for MyApp object. Since the functionality does not exist OOB, the prototype is consulted and in turn LookupDescFun function is executed.

If you are thinking this is an overkill, you may be right if this is all you want to do. Keep in mind that this coding practice will be more scalable, and ensures reusability.

02 February 2011

Siebel: Prototype in eScript - Part 2

The last example in prototypes dealt with extending a OOB data type, but that extension was done within the business service itself. Although the prototype can be defined only once and used multiple times, it is not really demonstrated well since the entire thing is handled within the same code. Here, let me take an opportunity to show how the prototype definition itself can be handled elsewhere.

Problem
Check whether the given string is a valid email address

Solution
Define the prototype to extend the OOB string object, and use it as many times as needed. To achieve this we define the prototype in the Application object.

Go to "Server Scripts" of 'Siebel Life Sciences' or similar, and define prototype.

(declarations)

String.prototype.IsEmail = CheckValidEmail;

Add a function 'CheckValidEmail' to the same application object.

function CheckValidEmail()

{

var rEmailPat = /^\w+[\w-\.]*\@\w+((-\w+)(\w*))\.[a-z]{2,3}$/;

return rEmailPat.test(this);

}

That's about it! Any string can now be tested for a valid email. We will quickly build a test function to demonstrate how this is used:

Service: COG Test Email

Method: Service_PreInvokeMethod

function Service_PreInvokeMethod (MethodName, Inputs, Outputs)

{

var sEmail = Inputs.GetProperty("Email");

Outputs.SetProperty("Valid", sEmail.IsEmail());

return (CancelOperation);

}

When you run this in the simulator, this should either return a 'true' or 'false' value depending on whether the supplied string is a valid email address. Now, a bit about how it works.

  1. First we define the prototype for the data type string with the statement String.prototype.IsEmail = CheckValidEmail'. This statement is executed when the application starts up.
  2. The above prototype points to a custom function 'CheckValidEmail'. This function uses a simple regular expression to test the validity of the entered string. It returns a 'true' when the string has the specified regex pattern, false otherwise
  3. None of the above has any effect until we actually invoke the 'IsEmail' function. When this function is used against the string object, Siebel checks the prototype since no such function exists OOB
  4. Return value from the function denotes whether the string 'sEmail' is a valid email address

Watch this space for one more example!

31 January 2011

Siebel: Script Libraries

Siebel 8 (or ST engine to be more specific) has a elegant way of calling business service methods. Script libraries provide the ability to call functions on a business service directly, no more is the need for building property sets and setting the parameters!

If you have not already used script libraries, do take a look. The reduced coding implies lesser mistakes, debugging time and easier maintenance! The simple demo below illustrates the usage.

Step 1:
Create the target business service 'COG Test Script Lib'. A custom function 'Echo' is defined here.

Service_PreInvokeMethod:

function Service_PreInvokeMethod (MethodName, Inputs, Outputs)

{

return (CancelOperation);

}

Echo:
function Echo (MyString)

{

return "Echoed: " + MyString;

}



Step 2:
Create the caller service 'COG Test Script Lib Call'. There is only one method here - 'Service_PreInvokeMethod', and the following code has to be input:

function Service_PreInvokeMethod (MethodName, Inputs, Outputs) {

var bsTest = TheApplication().GetService("COG Test Script Lib");

Outputs.SetProperty("Output", bsTest.Echo("abc"));

bsTest = null;

return (CancelOperation);

}



Compare this to the approach in earlier versions. In most probability you will be coding something like:

function Service_PreInvokeMethod (MethodName, Inputs, Outputs)

{

var bsTest = TheApplication().GetService("COG Test Script Lib");

var psIn = TheApplication().NewPropertySet();

var psOut = TheApplication().NewPropertySet();

psIn.SetProperty("MyString", "abc");

bsTest.InvokeMethod(psIn, psOut);

Outputs.SetProperty("Output", psOut.GetProperty("ReturnString"));

psOut = null;

psIn = null;

bsTest = null;

return (CancelOperation);

}


And, don't forget to add a line or two in the target service 'COG Test Script Lib' to set required properties in the output propertyset. Now, a simple 'bsTest.Echo("abc")' does the job. Isn't life simpler?

24 January 2011

Siebel: Prototype in eScript

I had mentioned about using prototypes in one of the previous posts, here's a drilldown into how things work.
Tucked away in a remote corner in the eScript reference of the Siebel Bookshelf is a single paragraph referring to prototypes. Common to javascript developers, prototype is not something that we bother about too often. Prototypes provide a highly reusable way of extending out of the box objects, with an optimal memory usage as a bonus.

How do we use Prototypes?
The best way to understand will be through an example. Let us consider a problem where we need to add x days to the given date and get the next working day (!= Saturday or Sunday).
We go about this problem by extending the Date object to support a new functionality - add x days and retrieve the next working day. For simplicity sake we keep the definition of prototype and the actual call together, however they may be located in different objects as well.
To demo the prototype define custom business service 'COG Get Working Day' in Siebel Tools or Client. Paste the following code in relevant sections:
(declarations)


Date.prototype.AddDaysToGetWrkDay = AddDaysToGetWrkDay;

AddDaysToGetWrkDay


function AddDaysToGetWrkDay(iDays, Outputs)

{

var iDateNew; var iOneDay = 24 * 60 * 60 * 1000; // day in milliseconds -
(hrs/day * min * sec * ms)
this.setMilliseconds(iDays * iOneDay);
if
(this.getDay() == 0 this.getDay() == 6) { // if sunday or saturday

this.AddDaysToGetWrkDay(1); // add one more day and check whether that falls
on working day

}

return this;

}

Service_PreInvokeMethod
function Service_PreInvokeMethod (MethodName, Inputs, Outputs)
{
try {
var dSomeDate = new Date("1/28/2011");
dSomeDate.AddDaysToGetWrkDay(1);
Outputs.SetProperty("New Date", dSomeDate);
return (CancelOperation);
}
catch(e){
throw(e);
}
finally {
dSomeDate = null;
}
}


When executed through simulator (or a call from placed from another service), the service returns the next working day - in the above example 31-Jan-2011. Read on to find out how.


Code Explanation

  1. 'Date.prototype.AddDaysToGetWrkDay = AddDaysToGetWrkDay' is the statement that tells the execution engine that there is a new prototype for Date object, and the extended functionality is provided by the function (or object) called 'AddDaysToGetWrkDay'. This is not synonymous with calling a function since there is no actual execution at this point. It is equivalent to a declaration.
  2. Next, define the function 'AddDaysToGetWrkDay'. This will act on the provided date object, which is referenced using 'this'. All it does is to add the given number of days to the date, check whether the new date falls on a Saturday or Sunday, continue adding more days if that is the case, and return the final date. Recursion is used to keep on adding days until it is not required.
  3. 'Service_PreInvokeMethod' just calls the extended function 'AddDaysToGetWrkDay' against the date object. When the actual call is made, the scripting engine looks at the Date object itself to check whether such a method is present, and then consults the prototype. Since such a prototype exists and points to a function, the function is executed to return the result

Note that the prototype itself may be defined only once, and the functionality is available thereon. Though this example is simple at its best, it does demonstrate how prototypes can be used to extend the objects.

Conclusion

Keep in mind the following:

  • Prototypes share the same memory space. Multiple invocations do not mean multiple copies
  • Prototypes can also be added later. Dynamic invocation can mean that you don't need to do everything in one place and at once
  • A prototype can also be extended further. For example, I can very well define another which says 'AddDaysToGetWrkDay.prototype.ExcludeDay' to selectively exclude certain days. For example, myDate.AddDaysToGetWrkDay(21).ExcludeDay("Tuesday") can return the working day 21 days from the given date, but which is not a Tuesday
  • From the above point you can observe that the methods can be executed in a 'chained' manner, which gives us a scalable solution that is easy to maintain (remember my OO reference in an earlier post?)
  • Use prototypes for reusable functions, that is when they yield better results

So, how do you want to use prototypes in your application?

17 January 2011

Siebel: Custom Functions for TheApplication

If you want to reuse code in Siebel, one of the common practices is to put it away in the business service and invoke those methods. This method, though is invaluable for complex operations, will become a painful process for simple things. When I say painful, it applies in some measure for both developers and the execution engine, reasons outlined below:
  1. Additional business service objects have to be created during execution, this may put some overhead in terms of performance (business service caching kept aside for now)
  2. Invoking most of the business services out there involves creation of property sets and calling them in a "proper" way. With the increased lines of code comes the increased complexity
  3. Developers have to "know" about the business service. This is a big problem in the longer term since code again gets littered everywhere inspite of the same functionality in a service
    There is a way to solve some of the above issues for simple reusable code (at least partially) - custom methods on TheApplication object. This uses a simple fact - all functions written in the application object will be available in any entity and method. Let us illustrate this with an example.

Problem: I need to get the description of a specified LOV. Though developers swear by LookupValue (and other Lookup) functions, there is little one can do about the 30 (or 50) char limit imposed by the data model. It is common to use Description (or some such field) for this purpose, but the code reuse is limited.

Solution: Write a LookupDesc function in the application object. Just edit the 'Siebel Life Sciences' (or any application) that is being used by your object manager. Create a new function called 'LookupDesc' and paste this code:

function LookupDesc(Type, Value)
{
try {
var sDesc = "";
var boLOV = TheApplication().GetBusObject("List Of Values");
var bcLOV = boLOV.GetBusComp("List Of Values");
with (bcLOV) {
ClearToQuery();
SetViewMode(AllView);
ActivateField("Description");
SetSearchExpr("[Type]='" + Type + "' AND [Value] = '" + Value + "'");
ExecuteQuery(ForwardOnly);
if (FirstRecord()) sDesc = GetFieldValue("Description");
} //with
return(sDesc);
}
catch(e) {
throw(e);
}
finally {
bcLOV = null;
boLOV = null;
}
}

Now, invoking the above function is by using a single line in applet, bc or a business service -

TheApplication().LookupDesc("MY_TYPE", "My Value")

This is also available in ScriptAssist against TheApplication, to make others aware of this function ofcourse!
A note of caution though - don't overdo this. I would recommend keeping the code here simple and tight, and to those functions where lot of reuse is foreseen.

30 December 2010

Siebel: User Defined Objects

Ever missed all the OOP goodness in Siebel? Although not used frequently, user defined objects provide you with some degree of control with hiding complexities in scripting. No, this will not help you attain OO nirvana - but you can start doing things with the custom objects and prototyping (another post for another day) to:

  • Hide complexity
  • Provide scalability
  • Save memory while doing the above

Here’s a simple example that demonstrates use of user-defined objects. To test, you simply copy the code in a new client business service and you are all set.
First the Service_PreInvoke method:

function Service_PreInvokeMethod (MethodName, Inputs, Outputs)
{
var qryBC;

qryBC = new GetRecord("Contact", "Contact", "[Id] = '0-1'", "First Name", "Last Name");
Outputs.SetProperty("First Name", qryBC.Values[3]);

Outputs.SetProperty("Last Name", qryBC.Values[4]);

return (CancelOperation);

qryBC = null;
}

Next comes the constructor:

function GetRecord ()
{
try {
var arrValue = new Array();
var iCount;

if (arguments.length < 4) TheApplication().RaiseErrorText("I need minimum four arguments - BO name, BC
name, SearchExpr and at least one field name.");

var bo = TheApplication().GetBusObject(arguments[0]);
var bc = bo.GetBusComp(arguments[1]);
with (bc){
ClearToQuery();
SetViewMode(AllView);

SetSearchExpr(arguments[2]);
for (iCount = 3; iCount < arguments.length; iCount++){
ActivateField(arguments[iCount]);
}
ExecuteQuery(ForwardOnly);
}

if (bc.FirstRecord()) {
for (iCount = 3; iCount < arguments.length; iCount++){
arrValue[iCount] = bc.GetFieldValue(arguments[iCount]);
}
}
this.Values = arrValue;
} // try

catch(e){
throw(e);
}

finally{
arrValue = null;
bc = null;
bo = null;
}
}

Now, the explanation:
Purpose:

Provide ability to query any given BO / BC and retrieve the specified field values

How did we do that:

First, we create an object called “qryBC”, which becomes instance of a class “GetRecord” when the constructor “GetRecord()” is executed. Since this is the very first exposure to the class/object concept, we are letting the constructor do all the work rather than splitting it up. At this time we also pass the arguments to the object, whereby the constructor will query and return you the results. For simplicity in further processing, we return an array with the query results. Note the use of ‘this’ in the constructor and the reference to the set values when retrieving results in PreInvoke method.

Never understood why OO beats procedural programming you say? You need to depend your friend Google to find out what you missed.(cross posted elsewhere)