private static extern bool Logoff(TS2KSvrObj lpUnk, ref Int32 plEnv);
 void CleanUp()
 {
     if (g_IServer != null)
     {
         try
         {
             Marshal.ReleaseComObject(g_IServer);
         }
         catch (Exception ex)
         {
             WriteErrorToLog(String.Format("General Error During CleanUp: {0} - {1}", ex.Message, ex.StackTrace));
         }
         finally
         {
             DumpErrorLog();
             GC.Collect();
             GC.WaitForPendingFinalizers();
             g_IServer = null;
             g_hTS2KEnv = 0;
         }
     }
 }
        public bool ManagedLogon(int TSModule, string TSWorkStation, string UserName, string UserPwd, string TSLicense)
        {
            bool result = false;
            int count = 0;

            if (g_IServer != null)
            {
                ManagedLogoff();
            }

            do
            {
                try
                {
                    count++;
                    g_IServer = (TS2KSvrObj)LogonNoWnd(TSModule, TSWorkStation, UserName, UserPwd, TSLicense, ref g_hTS2KEnv);
                    if (g_IServer != null && g_hTS2KEnv > 0)
                    {
                        result = true;
                        break;
                    }
                    WriteErrorToLog("Could not connect to TS2KServer. Try count: " + count);
                }
                catch (Exception ex)
                {
                    WriteErrorToLog(String.Format("General Error During Logon: {0} - {1}", ex.Message, ex.StackTrace));
                }
                CleanUp();
                Thread.Sleep(delay);
            } while (count < attempt);

            return result;
        }