Working With Sessions

Working with Sessions

The FairCom DB API .NET interface requires a session object to perform any data structure initialization or manipulation. The following steps must be executed within a session before any database or table operations are attempted:

  • Construct a CTSession object
  • Logon to a c-tree session by calling the CTSession.Logon() method.

Then after this initialization, all database and table operations should be performed. After these, in order to finalize the database operations, the following steps should be performed:

  • Logout from a c-tree session by calling the CTSession.Logout() method.
  • Destroy the CTSession object

 

Creating a Session Object

A valid session object is required to perform any session operation. The default parameter of the CTSession constructor is SESSION_TYPE.CTDB_SESSION.

// create a default CTSession object
CTSession ASession = new CTSession();
try
{
   // logon to session using default
   // server name, user name and password.
   CTSession.Logon();
}
catch (CTException err)
{
   Console.Write("Session logon failed with error {0}", err.GetErrorCode());
}

When a session object is created, we can specify the session type. There are three different session types:

SESSION_TYPE.CTREE_SESSION

Allocate a new session for logon only. No session or database dictionary files will be used. No database functions can be used with this session mode. You must allocate table handles using the session handle.

SESSION_TYPE.CTDB_SESSION

Allocate a new session making full usage of FairCom DB API .NET session and database dictionaries. With this session mode, a Session dictionary file must exist to perform a session logon and you need to connect to a database before attempting to perform operation on tables.

SESSION_TYPE.SQL_SESSION

Allocate a new session for FairCom DB SQL processing. This session type is available with certain restrictions.

Example

// Create a session object
CTSession ASession = new CTSession(SESSION_TYPE.CTDB_SESSION);

 

Creating a New Session Dictionary

When operating with sessions of type SESSION_TYPE.CTDB_SESSION or SESSION_TYPE.SQL_SESSION, a session dictionary file named ctdbdict.fsd is required before a session logon is performed. The session dictionary file ctdbdict.fsd is located by default either in the server directory (client/server application) or in the application directory (stand-alone application).

There could be situations where the FairCom DB API .NET session dictionary file does not exist because it was deleted or this is the very first time the system is being executed. In this case it is necessary to create a session dictionary file before attempting to log on to a session. It is important to note that only one session dictionary file is necessary for the normal operation of FairCom DB API .NET. Once created, the session dictionary file can be used for all database and table operations.

The following code fragment shows an example on how to create a new session dictionary file:

CTSession ASession = new CTSession();  
try
{
   ASession.Create("FAIRCOMS", "ADMIN", "ADMIN");
}
catch (CTException err)
{
   Console.WriteLine("Create session failed with error {0}", Err.GetErrorCode());
}

Note: Delphi users should use the equivalent method CreateSession() instead of Create().

In the server name, the full network address may be used (FAIRCOMS@10.0.0.1 or FAIRCOMS@my_machine.com for instance). For non-server applications, the parameter is ignored and may be set to NULL.

A valid user name is required to access the FairCom DB Server. When the FairCom DB server is first installed, only the default user is permitted server access. This user name, ADMIN, is intended for the database administrator. ADMIN is also the default user name for FairCom DB API .NET sessions. For non-server applications, the user name may be NULL. For server applications, see the c-tree Server Administrator’s Guide on how to create users and groups.

A valid user password is also required to access the FairCom DB Server. When the server is first installed, the default user ADMIN is associated with the default password, also ADMIN. For non-server applications, the user password may be NULL.

 

Session Logon and Logout

In order to perform any database operations, it is necessary to log on to a c-tree session. A session is terminated with a session logout.

To log on to a session, a CTSession object must be instantiated and then CTSession.Logon() method should be called to perform the session logon.

// Logon to a session
CTSession ASession = new CTSession();
try
{
   ASession.Logon("FAIRCOMS", "ADMIN", "ADMIN");
}
catch (CTException err)
{
   Console.Write("Session logon failed with error {0}\n", err.GetErrorCode());
}

Note: A useful sequence in code is to try to log on to the session, and if it fails with error FNOP_ERR (12), create the session dictionary and then log on again.

Example

CTSession ASession = new CTSession();
CTBOOL createit = false;

// try to logon to a session
try
{
   ASession.Logon("FAIRCOMS", "ADMIN", "ADMIN");
}
catch (CTException err)
{
   if (err.GetErrorCode() == 12)
   {
      createit = true;
   }
   else
      throw;
}
if (createit)
{
   ASession.Create("FAIRCOMS", "ADMIN", "ADMIN");
   try
   {
      ASession.Logon("FAIRCOMS", "ADMIN", "ADMIN");
   }
   catch (CTException err)
   {
      Console.Write("Logon failed with error {0}\n", err.GetErrorCode());
   }
}

When operations with the session are no longer needed, it is necessary to log out from the session by invoking method CTSession.Logout()

Example

CTSession ASession = new CTSession();

// logon to a session
try
{
   ASession.Logon("FAIRCOMS", "ADMIN", "ADMIN");
   // ... perform some other operations ..
   ASession.Logout();
}
catch (CTException err)
{
   Console.Write("Logon or Logout failed with error {0}\n", err.GetErrorCode());
}


 

Session Properties

The default session properties are suitable for most FairCom DB API .NET applications. Advanced developers may need to tune FairCom DB API .NET to meet application requirements. Use CTSession.SetSessionParams() to set the following properties:

Default Session Parameters

Property Explanation Default
SESSION_PARAM.BUFS Index file buffers 10
SESSION_PARAM.FILS File structure blocks 32
SESSION_PARAM.SECT Node sectors 32
SESSION_PARAM.DBUFS Data file buffers 10
SESSION_PARAM.USERPROF User profile mask 513

The default SESSION_PARAM.USERPROF value of 513 tells single-user, transaction-control applications to remove the auxiliary log files S*.FCS and L*.FCS upon successful termination of the application, and also to remove the automatic key transformation.

The table below presents all possible values for the SESSION_PARAM.USERPROF parameter.

User Profile Values (USER_PROF enum)

Keyword Value Explanation
NTKEY 1 Do not perform auto tfrmkey
SAV_ENV 2 Savenv mode for transactions
SQL 4 Enable SQL support
SERIAL 8 Enable strict serialization
NDATA 32 Do not perform auto date - UNIFRMAT conversion
LOCLIB 64 Use a local library, not server
PTHTMP 128 Add tmpname to input path, otherwise use system tmpname
CODCNV 256 Auto language conversion
CLRCHK 512 Clear transaction logs
CUSTOM 1024 Custom server application
ENCRYPT 2048 Enable encryption


Example

// set a different user profile before logging on to a session
CTSession ASession = new CTSession();

try
{
   // set the new profile
      ASession.SetParam(SESSION_PARAM.USERPROF, (USER_PROF.NTKEY |
      USER_PROF.CLRCHK));
   // logon to a session
   ASession.Logon("FAIRCOMS", "ADMIN", "ADMIN");
}
catch (CTException err)
{
	Console.Write("Session logon failed with error {0}\n", err.GetErrorCode());
}

 

Server and User Name Properties

Once a session is active, the user may retrieve the server name for the session with CTSession.GetServerName(). Retrieve the user name by calling the CTSession.GetUserLogonName() method. Please refer to the example in Active Property.

 

Active Property

A session is active if the user has logged on to a valid session dictionary using CTSession.Logon(). To render a session inactive, log off using CTSession.Logout(). To verify the status of the session, use CTSession.IsActive().

//if session is active, retrieve the server name and user logon name 
if (ASession.IsActive())
{
   Console.Write("Server name: {0}\n", ASession.GetServerName());
   Console.Write("User name  : {0}\n", ASession.GetUserLogonName());
}

 

Path Property

The default path for client/server applications is the server directory, while the default path for non-server applications is the application directory. If, for any reason, there is the need to modify the location of the session dictionary, CTSession.SetPath() may be used before creating and/or logging on to the session. CTSession.GetPath() may be used to retrieve the path for an active session.

Using this property, it is even possible to have multiple session dictionaries, in separate directories. This is not required, since the concepts of restricting access to different users to diverse tables or databases may be implemented inside a unique session dictionary.

The example below shows how to use the CTSession.SetPath() function to create a session dictionary file in a user specified directory, instead of the default directory:

CTSession ASession = new CTSession();
try
{
   ASession.SetPath("\new\session");
   ASession.Create("FAIRCOMS", "ADMIN", "ADMIN");
}
catch (CTException err)
{
   Console.Write("Create session failed with error {0}\n", err.GetErrorCode());
}

 

Managing Databases

Once the user performs a successful Session logon, the session object can be used to operate on databases.

Every time a new database is created, or an existing database is added to a session, the database properties such as database name and path are placed in an entry of the database dictionary file.

Every time a user activates a database by connecting to it using the CTDatabase.Connect() method, the database is placed in a list of active (connected) databases within the session. When a database is deactivated or disconnected by the CTDatabase.Disconnect() method, the database is removed from the list of active databases.

 

Creating a New Database

Use the CTSesson.CreateDatabase() method to create a new database. CTSession.CreateDatabase() takes a database name and the path where the database dictionary file is to be created. If the database path is empty ("") the database is created in the server directory, for client/server applications, or in the current directory for standalone applications.

// create a new database MyDatabase
try
{
   ASession.CreateDatabase("MyDatabase", "");
}
catch (CTException err)
{
   Console.Write("Create database failed with error {0}\n", err.GetErrorCode());
}

CTSession.CreateDatabase() creates a new database dictionary file with the database name and extension .fdd (FairCom Database Dictionary). Using the example above, the database dictionary file created is MyDatabase.fdd.

 

Adding an Existing Database

An existing database may be added or imported to a session by calling the CTSession.AddDatabase() method. Use CTSession.AddDatabase() to add an existing database to the current session. CTSession.AddDatabase() takes a database name and the path where the database is located.

// add MyDatabase to the current session
try
{
   ASession.AddDatabase("MyDatabase", "");
}
catch (CTException err)
{
   Console.Write("Add database failed with error {0}\n", err.GetErrorCode());
}

 

Dropping a Database

When you drop a database from a session, the database information is removed from the session dictionary, but the database dictionary file is left untouched. The drop database operation can be reversed with an add database operation. Drop a database from a session by calling CTSession.DropDatabase() method.

// drop MyDatabase from current session
try
{
   ASession.DropDatabase("MyDatabase");
}
catch (CTExceptionv err)
{
   Console.Write("Drop database failed with error {0}\n", err.GetErrorCode());
}

 

Deleting a Database

CTSession.FirstDatabase() will retrieve the name and path of the first database in a session. If the session has no databases, CTSession.FirstDatabase() returns false (false).

 

First Database

CTSession.FirstDatabase() will retrieve the name and path of the first database in a session. If the session has no databases, CTSession.FirstDatabase() returns false (false).

 

Next Database

CTSession.NextDatabase() will retrieve the name and path of the next database in a session. CTSession.NextDatabase() returns false (false) when no more databases exist for the current session.

// display all databases in a session
CTDBRET DisplayDatabases(CTSession ASession)
{
   CTDBRET Retval = CTDBRET_OK;
   try
   {
      StringBuilder dbName = new StringBuilder();
      StringBuilder dbPath = new StringBuilder();
  
      if (ASession.FirstDatabase(out dbName, out dbPath))
      do
      {
          Console.Write("Database: {0} Path: {1}\n", dbName.ToString(),
          dbPath.ToString());
      }
      while (ASession.NextDatabase(out dbName, out dbPath);
   }
   catch (CTException err)
   {
     Retval = err.GetErrorCode();
   }
   return Retval;
}

 

Find Database

CTSession.FindDatabase() locates a specific database given the database name and, if the database exists, retrieves the database path. If a database cannot be found, CTSession.FindDatabase() returns false (false).

// return true if database exists or false if database does not exits
CTBOOL DatabaseExist(CTSession ASession, string dbName)
{
   CTBOOL Retval;
   StringBuilder dbPath = new StringBuilder();
  
   try
{
      Retval = ASession.FindDatabase(dbName, out dbPath);
   }
   catch (CTException err)
   {
      Retval = false;
   }
   return Retval;
}


 

Database UID (Unique Identifier)

When a database is created or added to a session, an automatic and unique identifier (UID) is associated with the database. A database UID is unique within the session.

A database UID is an unsigned long value that can be used as an alternative method to operate on databases, once the database is created or added to the session.

 

Find Database by UID

The overloaded method CTSession.FindDatabase() locates a database given the database UID and retrieves the database name and path. The following example shows how to implement a database connect procedure using the database UID instead of the database name.

// Database Connect using UID
CTDatabase ConnectByUID(CTSession ASession, ULONG uid)
{
   StringBuilder dbName = new StringBuilder();
   StringBuilder dbPath = new StringBuilder();
   CTDatabase Retval = null;

   if (ASession.FindDatabase(uid, out dbName, out dbPath)
   {
      Retval = new CTDatabase(ASession);
      if (Retval != null)
      {
         Retval.Connect(dbName);
      }
      else
      {
         throw CTException(CTDBRET_NOMEMORY);
      }
   }
   else
   {
      throw CTException(FNOP_ERR);
   }
   return Retval;
}

 

Working with Sessions without Dictionary Support

There may be situations where it is necessary to operate with a table that does not belong to a database, or where a session or database dictionary file is not required. For these situations the user may want to create a session object of type SESSION_TYPE.CTREE_SESSION.

// create a session object without dictionary support
CTSession ASession = new CTSession(SESSION_TYPE.CTREE_SESSION);
// Logon to a session
try
{
   ASession.Logon("FAIRCOMS", "ADMIN", "ADMIN");
}
catch (CTException err)
{
   Console.Write("Session logon failed with code {0}\n", err.GetErrorCode());
}

The CTSession.Logon() call above will perform a c-tree logon but it will not attempt to open a session dictionary file. The same result is obtained if a normal SESSION_TYPE.CTDB_SESSION or SESSION_TYPE.SQL_SESSION session is allocated but the method CTSession.SetLogonOnly() is called before CTSession.Logon().

// create a session object without dictionary support
CTSession ASession = new CTSession();

// Logon to a session
try
{
   ASession.SetLogonOnly();
   ASession.Logon("FAIRCOMS", "ADMIN", "ADMIN");
}
catch (CTException err)
{
   Console.Write("Session logon failed with code {0}\n", err.GetErrorCode());
}


 

Session Dictionary

The session dictionary is a collection of databases, and each record of the session dictionary file contains the information of a particular database. In general, just one session dictionary file exists, ctdbdict.fsd, located by default in the server directory (client/server development) or in the application directory (stand-alone application). The table below represents the general layout of a session dictionary file:

Session Dictionary Layout

Field Type Length Description
TYPE CT_INT4 4 Record type: 1-database 2-table 3-index
STATUS CT_INT4 4 Record status: 0-status ok 1-reserved
NAME CT_FSTRING 128 Name of database or table or index
LINK CT_FSTRING 128 Name of table if record type is 3-index
LINKNBR CT_INT4 4 Table UID if record type is 3-index
PATH CT_FSTRING 256 Path of database dictionary, data or index
SUPEXT CT_FSTRING 16 Super file extension (if super file is used)
DATEXT CT_FSTRING 16 Data file extension (usually .DAT)
IDXEXT CT_FSTRING 16 Index file extension (usually .IDX)
VERSION CT_INT4 4 Record version: 0x00010000 (version 1.0)
COUNTER CT_INT4 4 Deprecated.
UID CT_INT4 4 UID for database or table or index
OWNER CT_FSTRING 128 Name of owner - used by the c-treeSQL server
MIRROR_NAME CT_FSTRING 128 Name of mirrored file.
MIRROR_PATH CT_FSTRING 128 Path of mirrored file.
RESERVED CT_ARRAY 3128 Reserved for future use

This information is included for general information on the session dictionary structure. FairCom DB API has appropriate functions to retrieve any needed information from the session dictionary, such as the database UID or path.

A session dictionary file has several different record types:

  • Database records (the field Type set to 1) holds information about databases.

A special type four record which maintained the COUNTER field has been been deprecated as of FairCom DB V9.0.