How can I get the SID in Serverside scripting?

2 minute read time.
The SID is the session ID value. The SID may be wanted if you are building a string that represents a hyperlink that will be returned to the browser. The SID after all only is needed for a new web request, we do not actually need it within server side scripts normally as there we are already in the context of the session.

I can think of 3 ways that the session information can be obtained.

1) In Create Scripts we can use the Values() collection to return the SID. So we can test

Valid = false; 
ErrorStr = Values("SID");


This will not work in Table Level scripts.

2) In Table Level scripts and where Values() will not return the SID we can take advantage of the CRM.URL() method. This is a cheat.

The CRM.URL() method is used to build a URLs and hyperlinks that include all of the current contextual information, which of course includes the SID we want.

So in a tablelevel script UpDateRecord event function we can test:


Valid = false: 
ErrorStr = CRM.URL(200);

Here the value 200 is the Action code for the CompanySummary screen and the eWare.URL method returns a string that looks like:

/CRM/eware.dll/Do?SID=126291409626649 &Act=200 &Mode=1 &CLk=T &Key0=1 &Key1=41 &Key2=51

We can parse the string returned by the CRM.URL() to obtain the SID. For example:


function UpdateRecord() 
{ 
Valid = false; 
ErrorStr ="SID="; 
var strPath = CRM.URL(200); 
var arrayFullKeys = strPath.split("?"); 
var arrayKeys = arrayFullKeys[1].split(" &"); 
for (var i=0;i ") 
{ 
ErrorStr += arrayValue[1]; 
} 
} 
}

3)

Another less satisfactory method uses the fact that the session id of the user is recorded in the Activity table. In a table level script we can get this using the following


function UpdateRecord() 
{ 
var strSQL = "select * from activity where acty_activityid = (select max(acty_activityid) from activity where acty_userid ="+CurrentUser.user_userid+")" 
var myQuery = CRM.CreateQueryObj(strSQL,""); 
myQuery.SelectSQL(); 

Valid = false; 
ErrorStr = myQuery.FieldValue("acty_SID"); 
} 


Note: Entries into the Activity table are not actually immediate upon the user logging onto the system. The Activity table is updated automatically only every minute, so there maybe a pause of upto 60 seconds after the user has logged on before an entry is made in the table. This means that it is probably better to use my second method or to only use the 3rd method where detached (delayed) table level scripts are used.