Example #1
0
void CFMSServer::DeleteScheduledRemindersL()
    {
    FLOG(_L("CFMSServer::DeleteScheduledRemindersL >>"));
    
    TScheduleEntryInfo2                     ret;
    TInt                                    err;    
    RScheduler                              sc;
    TTime                                   t; 
    TTsTime                                 time;
    TSchedulerItemRef                       scitem; 
    CArrayFixFlat<TSchedulerItemRef>*       aSchRefArray = new CArrayFixFlat <TSchedulerItemRef>(5);
    TScheduleFilter                         aFilter(EAllSchedules);
    User::LeaveIfError( sc.Connect() ); 
    CleanupClosePushL( sc );
    CleanupStack::PushL(aSchRefArray);

    User::LeaveIfError( sc.GetScheduleRefsL( *aSchRefArray,aFilter) );
    FLOG(_L("Schedule items: "));
    for ( TInt i=0; i<aSchRefArray->Count(); ++i  )
    {
    TSchedulerItemRef it = (*aSchRefArray)[i];
    if ( it.iName == TUid::Uid(KFMSServerUid).Name()  )
        {
        TScheduleState2 sc_state;
        CArrayFixFlat<TScheduleEntryInfo2>*  sc_entries = new CArrayFixFlat <TScheduleEntryInfo2>(5);
        CArrayFixFlat<TTaskInfo>*            sc_tasks  = new CArrayFixFlat <TTaskInfo>(5);
        TTsTime                              sc_duetime;
        CleanupStack::PushL( sc_entries );
        CleanupStack::PushL( sc_tasks );
        FLOG (_L("%d. schedule handle: %d name:'%S'"),i,it.iHandle, &(it.iName) );

        err = sc.GetScheduleL ( it.iHandle , sc_state, *sc_entries,*sc_tasks,sc_duetime ); // xx

        TDateTime  dtm = sc_duetime.GetLocalTime().DateTime();
        FLOG(_L("   schedule duetime:%d:%d"), dtm.Hour(), dtm.Minute());

        if ( err ) FLOG(_L("     schedule  sc get err %d"),err);
        else 
            {
            for ( TInt k=0; k<sc_entries->Count();++k)
                {
                TScheduleEntryInfo2 sc_entry = (*sc_entries)[k];
                ret = sc_entry;
                TTime sctime = sc_entry.StartTime().GetLocalTime();
                FLOG(_L("         schedule entry %d int-type:%d int:%d start: %d:%d"),k,sc_entry.IntervalType(),sc_entry.Interval(),sctime.DateTime().Hour(),sctime.DateTime().Minute());
                }

            for ( TInt j=0; j<sc_tasks->Count();++j)
                {
                TTaskInfo sc_task = (*sc_tasks)[j];
                FLOG(_L("         schedule task  %d  '%S'"),sc_task.iTaskId,&(sc_task.iName) );
                if ( sc_task.iName==TUid::Uid(KFMSServerUid).Name() )
                    {
                    FLOG(_L("          schedule DeleteTask %d"),sc_task.iTaskId);
                    User::LeaveIfError( sc.DeleteTask(sc_task.iTaskId) );
                    }
                }
            }

        FLOG(_L("     DeleteSchedule %d"),it.iHandle);
        err = sc.DeleteSchedule(it.iHandle );
		FLOG(_L("Delete status of tasks = %d"), err);

        CleanupStack::PopAndDestroy( sc_tasks );
        CleanupStack::PopAndDestroy( sc_entries );
        }
    }
    CleanupStack::PopAndDestroy( aSchRefArray );
    CleanupStack::PopAndDestroy(&sc);
    
    FLOG(_L("CFMSServer::DeleteScheduledRemindersL <<"));
    }
//---------------------------------------------------------------------------
TData __fastcall MyArhiv::GetFDataTag(TDateTime DateArhiv, int IDTag)
{
 struct TData         Ret;
 static TDateTime     Old;
 static char          NameCurDir[255];
 static AnsiString    TekDir         ;
 static bool          first=true     ;
 int                  handle_file    ;
 static AnsiString    OldName=""     ;
 static unsigned long kb = 0L;
 static bool          Error = true;
 static double tim;
 if (first) // определить текущую директорию                           
  {
   GetCurrentDirectory(255,NameCurDir);
   TekDir    = NameCurDir;
   first     = false     ;
  }
 if (IDTag>=10000)
  {
   Ret.Status  = 1;
   Ret.Val     = 0;
   Ret.YesData = true;
   return Ret;
  }
 if (Old!=DateArhiv)
  {
   AnsiString ARHIV = "ARHIV";
   AnsiString YEAR  = DateArhiv.FormatString("yyyy");
   AnsiString MON   = DateArhiv.FormatString("mm")  ;
   AnsiString DAT   = DateArhiv.FormatString("dd")  ;
   AnsiString HOUR  = DateArhiv.FormatString("hh")  ;
   int min = StrToInt(DateArhiv.FormatString("nn"));
   int sec = StrToInt(DateArhiv.FormatString("ss"));
   Old = DateArhiv;
   AnsiString  NameFile   = TekDir+"\\"+ARHIV+"\\"+YEAR+"\\"+MON+"\\"+DAT+"\\" + HOUR +".dat";
   Error=true;
   if ((handle_file=_open(NameFile.c_str(),O_RDONLY|O_BINARY))>0) // чтение информации из файла
    {
/*     unsigned int  kb_zag  = sizeof(int)*ActiveArhiv->CountTags+sizeof(int);
     unsigned int  len_buf = ((sizeof(double)+sizeof(int))*ActiveArhiv->CountTags+sizeof(double))*3600; //  ((    значение и статус   ) *кол-во тэгов + дата и время) 60 сек * 60 мин
     unsigned char *buf; */
     if (OldName!=NameFile) // разбор заголовка
      {
       lseek(handle_file,0L,SEEK_SET)    ;
       Error = false;
       _read(handle_file,&kb,sizeof(int)); // размер заголовка
       if (kb == sizeof(int)*ActiveArhiv->CountTags+sizeof(int)) // размер заголовка должен соответствовать количеству архивных тэгов
        {
         if (_read(handle_file,FArhivIDTags,sizeof(int)*ActiveArhiv->CountTags)!=(signed int)(sizeof(int)*ActiveArhiv->CountTags)) Error=true;
        }
       else Error = true;
       OldName = NameFile;
      }
     else Error = false;
     if (!Error)
      {
       unsigned long sm = min * 60 + sec;
       sm = kb + sm * ((sizeof(double)+sizeof(int))*ActiveArhiv->CountTags+sizeof(double));
       sm = lseek(handle_file,sm,SEEK_SET);
       if (_read(handle_file,(unsigned char *)&tim,sizeof(double))!=sizeof(double)) Error=true;
       else if (_read(handle_file,(unsigned char *)FArhivValTags,(unsigned int)(sizeof(double)*ActiveArhiv->CountTags))!=(signed int)(sizeof(double)*ActiveArhiv->CountTags)) Error=true;
       else if (_read(handle_file,(unsigned char *)FArhivStatTags,sizeof(int)*ActiveArhiv->CountTags)!=(signed int)(sizeof(int)*ActiveArhiv->CountTags))      Error=true;
      }
     _close(handle_file);
     handle_file = -1;
    }
  }
 if ((tim==0)||(Error)) { FDataTag.YesData=false;FDataTag.Val=0;FDataTag.Status=1; }
 else
  {
   FDataTag.YesData=false;
   for (int pc=0;pc<FCountTags;pc++)
    {
     if (FArhivIDTags[pc]==IDTag)
      {
       FDataTag.Val     = FArhivValTags[pc];
       FDataTag.Status  = FArhivStatTags[pc];
       FDataTag.YesData = true;break;
      }
    }
   if (!FDataTag.YesData) { FDataTag.Val=0;FDataTag.Status=1; }
  }
 Ret = FDataTag;
 return Ret;
}
Example #3
0
//---------------------------------------------------------------------------
void __fastcall TFormLog::ButtonLogClick(TObject *Sender)
{
        if(EditQRZ->Text=="") return;

        int H;
        AnsiString LogName = ThePath + "\\stream.adi";

        if(FileExists(LogName))
        {
           H = FileOpen(LogName,fmOpenReadWrite);
           if(H<0)
           {
              Application->MessageBox("Cannot write to log","IZ8BLY PSK31 Lab",MB_OK | MB_ICONSTOP);
              return;
           }
           FileSeek(H,0,2);
        }
        else
        {
           H = FileCreate(LogName);
           if(H<0)
           {
              Application->MessageBox("Cannot write to log","IZ8BLY PSK31 Lab",MB_OK | MB_ICONSTOP);
              return;
           }
           FileWriteString(H,"Created by IZ8BLY PSK31 Lab\r\n<EOH>\r\n");
        }

        AnsiString Linea;

        TDateTime TD;
        if(UTCTimeLog)
        {
           SYSTEMTIME SystemTime;
           GetSystemTime(&SystemTime);
           TD = SystemTimeToDateTime(SystemTime);
        }
        else
        {
           TD = TDateTime().CurrentDateTime();
        }

        Linea = FormatAdif("CALL",EditQRZ->Text) +
                FormatAdif("NAME",EditName->Text)+
                FormatAdif("QTH",EditQTH->Text)+
                FormatAdif("RST_RCVD",EditRSTReceived->Text)+
                FormatAdif("RST_SENT",EditRSTSent->Text)+
                FormatAdif("FREQ",EditFrequency->Text)+
                FormatAdif("MODE","STREAM")+
                FormatAdif("QSO_DATE",TD.FormatString("yyyymmdd"))+
                FormatAdif("TIME_ON",TD.FormatString("hhmm"))+
                FormatAdif("COMMENT",EditComments->Text)+
                "<EOR>\r\n";

        FileWriteString(H,Linea);
        FileClose(H);

        char oldclip[2048];
        Clipboard()->GetTextBuf(oldclip,2048);

        Clipboard()->SetTextBuf(Linea.c_str());
        SendMessage(HWND_BROADCAST,IZ8BLY,0,0);
        Clipboard()->SetTextBuf(oldclip);

        ButtonLog->Enabled = false;
}
void CDummyCalendarApp::AddEntryL(TInt aNumToAdd, TBool isParent, TBool isRepeat)
	{
	test.Next(_L("Adding entries"));

	TBuf<50> summary;
	TBuf<50> location;
	TBuf<50> description;

    

	iEntries.ResetAndDestroy();
	for (TInt index=0; index<aNumToAdd; index++)
		{
		TBuf8<255> buf;
		buf.Append(_L("GuidId"));
		buf.AppendNum(index);
		HBufC8* guid = buf.AllocLC();   // need to be pushed to ...

		CCalEntry::TType entryType=(index%2==0)?CCalEntry::ETodo:CCalEntry::EAppt;

		CCalEntry* entry = NULL;
		if(isParent)
			{
			entry = CreateCalEntryL(entryType, guid);
			}
		else
			{
			TTime localTime(KRecurrIdLocalTime);
			TCalTime recurrenceId;
			recurrenceId.SetTimeLocalL(localTime);
			entry = CCalEntry::NewL(entryType, guid, CCalEntry::EMethodAdd, 1, recurrenceId, CalCommon::EThisAndFuture);
			}
		CleanupStack::Pop(guid);
		iEntries.AppendL(entry);

		TInt year = -1;
		TInt month = -1;
		TInt day = -1;
		
		if (isParent)
		    {
    		year = index % 5 + 2001;    // Any year in the range: 2001 - 2005
    		month = index % 12;         
    		day = index % 28;
		    }
        else
            {
            // if this is a child entry, use the recurrence local time as the entry start time 
            // so it won't be out of range
            TCalTime recurrId = entry->RecurrenceIdL(); 
            TDateTime localTime = recurrId.TimeLocalL().DateTime();               
            year = localTime.Year();
            month = localTime.Month();
            day = localTime.Day();    
            }
		
		TTime start(TDateTime(year, (TMonth)month, day, 0, 0, 0, 0));
		TTime end(TDateTime(year, (TMonth)month, day, 0, 0, 0, 0));
		end += TTimeIntervalDays(1);

		SetEntryStartAndEndTimeL(entry,start,end);
				
		RandomText(summary);
		entry->SetSummaryL(summary);
		
		RandomText(location);
		entry->SetLocationL(location);
		
		RandomText(description);
		entry->SetDescriptionL(description);

		if(isRepeat)
			{
			//create a daily repeat rule and make sure its repeat start\end date is within the deleting time range
			TCalRRule rpt(TCalRRule::EDaily);
			rpt.SetInterval(1);
			TCalTime repeatStart;
			TCalTime repeatend;
			if(isParent)
				{
				//make sure the repeat time is within the delete time range
				repeatStart.SetTimeLocalL(TDateTime(2000, EJune, 0, 0, 0, 0, 0));
				repeatend.SetTimeLocalL(TDateTime(2006, EJune, 0, 0, 0, 0, 0));
				}
			else if (index<aNumToAdd/2)
				{
                // if this is a child entry, use the entry's recurrance time as repeating rule
                // start time 
                TCalTime recurrId = entry->RecurrenceIdL(); 
				
				// make sure the repeat time is within the delete time range for the first half entries
				repeatStart.SetTimeLocalL(recurrId.TimeLocalL());	// June 1, 2003 00:00:00
				repeatend.SetTimeLocalL(recurrId.TimeLocalL() + TTimeIntervalMonths(1));  // July 1, 2003 00:00:00
				}
			else
				{
				//make sure the repeat time is out of the delete time range for the second half entries
				repeatStart.SetTimeLocalL(TDateTime(2003, EJune, 0, 0, 0, 0, 0));
				repeatend.SetTimeLocalL(TDateTime(2007, EJune, 0, 0, 0, 0, 0));
				}

			rpt.SetDtStart(repeatStart); 
			rpt.SetUntil(repeatend);
			entry->SetRRuleL(rpt);
			}
		}
	
	TInt entriesStored(0);
	iLocalEntryView->StoreL(iEntries, entriesStored); //temp
	test(entriesStored == iEntries.Count());
	}
Example #5
0
UnicodeString DateTimeToString(TDateTime DateTime)
{
  return DateTime.FormatString(L"");
}
// 	print a date and time to log in a readable format:
void LbsTestUtilities::PrintfDateTimeToDebugLog(TTime aTime)
	{
	TDateTime datetime = aTime.DateTime();	
	TESTLOG8(ELogP2,"%d :%d :%d :%d on %d/%d/%d", datetime.Hour(), datetime.Minute(), datetime.Second(), datetime.MicroSecond(), datetime.Day() + 1, datetime.Month() + 1, datetime.Year());	
	}
Example #7
0
//---------------------------------------------------------------------------
void __fastcall TBookNotAcceptListForm::FormShow(TObject *Sender)
{
	CString szSQL;
        unsigned short year,month,day;
	edtDays->Text="2";

	m_lstCorpID.Add("");
	lstCorp->Items->Add("全部");

	szSQL="select * from DepartCorp order by dc_code";
	RunSQL(dm1->Query1,szSQL,true);
	while(!dm1->Query1->Eof)
	{
		m_lstCorpID.Add(dm1->Query1->FieldByName("dc_code")->AsString.c_str());
		lstCorp->Items->Add(dm1->Query1->FieldByName("dc_name")->AsString);

		dm1->Query1->Next();
	}
	lstCorp->ItemIndex=0;

	m_lstDepartID.Add("");
	lstDepart->Items->Add("全部");
	szSQL="select * from StockDepart order by sd_code";
	RunSQL(dm1->Query1,szSQL,true);
	while(!dm1->Query1->Eof)
	{
		m_lstDepartID.Add(dm1->Query1->FieldByName("sd_code")->AsString.c_str());
		lstDepart->Items->Add(dm1->Query1->FieldByName("sd_name")->AsString);
		dm1->Query1->Next();
	}
	lstDepart->ItemIndex=0;

	m_lstAskDepID.Add("");
  lstAskDep->Items->Add("全部");
	szSQL="select * from DicDepart,DepartCorp where dc_code=substring(dd_code,1,2) order by dd_code";
	RunSQL(dm1->Query1,szSQL,true);
	while(!dm1->Query1->Eof)
	{
		m_lstAskDepID.Add(dm1->Query1->FieldByName("dd_code")->AsString.c_str());
		lstAskDep->Items->Add(dm1->Query1->FieldByName("dc_name")->AsString
    	+dm1->Query1->FieldByName("dd_name")->AsString);
		dm1->Query1->Next();
	}
	lstAskDep->ItemIndex=0;

	m_lstFactID.Add("");
	lstFact->Items->Add("全部");
	szSQL="select * from Manufactur order by mf_code";
	RunSQL(dm1->Query1,szSQL,true);
	while(!dm1->Query1->Eof)
	{
		m_lstFactID.Add(dm1->Query1->FieldByName("mf_code")->AsString.c_str());
		lstFact->Items->Add(dm1->Query1->FieldByName("mf_shortname")->AsString);
		dm1->Query1->Next();
	}
	lstFact->ItemIndex=0;

        TDateTime tNow;
        tNow=GetSysTime(false);
        tNow.DecodeDate(&year,&month,&day);
        DateTimePicker1->Date=tNow;
        DateTimePicker2->Date=tNow;
}
Example #8
0
    TBool CDataWrapperBase::GetDateTimeFromConfig(const TDesC& aSectName,  TDateTime& aResult)
    	{
    	TInt year , month , day , hour , minute, second, microsecond ;
    	
    	// Fields
    	_LIT(KYear,			"year");
    	_LIT(KMonth,		"month");
    	_LIT(KDay,      	"day");
    	_LIT(KHour,         "hour");
    	_LIT(KMinute,		"minute");
    	_LIT(KSecond,		"second");
    	_LIT(KMicrosecond,  "microsecond");

    	TBool ret = ETrue ; 
    	if ( !GetIntFromConfig( aSectName, KYear , year))
    		{
			ret=EFalse;
			}
    	if ( !GetIntFromConfig( aSectName, KMonth , month))
    		{
			ret=EFalse;
			}     	 
    	if ( !GetIntFromConfig( aSectName, KDay, day))
    		{
			ret=EFalse;
			} 
    	if ( !GetIntFromConfig( aSectName, KHour, hour))
    		{
			ret=EFalse;
			} 
    	if ( !GetIntFromConfig( aSectName, KMinute , minute))
    		{
			ret=EFalse;
			}  
    	if ( !GetIntFromConfig( aSectName, KSecond , second))
    		{
			ret=EFalse;
			}  
    	if ( !GetIntFromConfig( aSectName, KMicrosecond , microsecond))
    		{
			ret=EFalse;
			} 
    	if ( ret )
			{
			TMonth amonth ;
			switch (month) 
			  {
			  case 1:
			       amonth = EJanuary ;
			       break ;
			  case 2:
			       amonth = EFebruary  ;
		           break ;
			  case 3 :
			       amonth = EMarch  ;
			       break ;
			  case 4: 
			       amonth = EApril ;
			       break ;
			  case 5:
			       amonth = EMay  ;
		           break ;
			  case 6 :
			       amonth = EJune ;
			       break ;
			  case 7 :
			       amonth = EJuly ;
			       break ;
			  case 8 :
			       amonth = EAugust ;
			       break ;
			  case 9 :
			       amonth = ESeptember ;
			       break ;
			  case 10 :
			       amonth = EOctober ;
			       break ;
			  case 11 :
			       amonth = ENovember ;
			       break ;
			  case 12:
			       amonth = EDecember ;
			       break ;
			  default :
			       return ret ;
			  }
			
			aResult.Set(year,amonth ,day,hour,minute,second,microsecond);
			}
    	 
    	return ret ;
    	}
//---------------------------------------------------------------------------
void TGJVQSOEditFrame::selectEntry( BaseContact *slct )
{
   selectedContact = slct;   // contact from log list selected

   FirstUnfilledButton->Visible = false;
   CatchupButton->Visible = false;

   screenContact.copyFromArg( *slct );
   showScreenEntry();

   PriorButton->Enabled = getPriorContact();
   NextButton->Enabled = getNextContact();
   InsertAfterButton->Enabled = getNextContact();  // dont allow insert after last contact

   MainOpComboBox->Text = screenContact.op1.c_str();
   SecondOpComboBox->Text = screenContact.op2.c_str();
   if ( !contest->isReadOnly() && (screenContact.contactFlags & TO_BE_ENTERED || catchup))
   {
      // Uri Mode - catchuping QSOs from paper while logging current QSOs
      // and we need to set the date/time from the previous contact
      TimeEdit->ReadOnly = false;
      DateEdit->ReadOnly = false;

      int tne = screenContact.time.notEntered(); // partial dtg will give +fe
      // full dtg gives -ve, none gives 0
      if ( tne == 0 )
      {
         BaseContact * pct = getPriorContact();
         if ( pct )
         {
            screenContact.time = pct->time;
            DateEdit->Text = screenContact.time.getDate( DTGDISP ).c_str();
            TimeEdit->Text = screenContact.time.getTime( DTGDISP ).c_str();
         }
         else
         {
            // use contest start time
            TDateTime DTGStart = CanonicalToTDT(contest->DTGStart.getValue().c_str());
            DateEdit->Text = DTGStart.FormatString("dd/mm/yy");
            TimeEdit->Text = DTGStart.FormatString("hh:nn");
            dtg time(false);
            time.setDate( DateEdit->Text.c_str(), DTGDISP );
            time.setTime( TimeEdit->Text.SubString(1, 5).c_str(), DTGDISP );
            screenContact.time = time;
         }
         int selpt = DateEdit->Text.Length();
         if ( selpt > 2 )
         {
            DateEdit->SelStart = 1;
            DateEdit->SelLength = 1;
         }

         selpt = TimeEdit->Text.Length();
         if ( selpt > 0 )
         {
            TimeEdit->SelStart = selpt - 1;
            TimeEdit->SelLength = 1;
         }
      }
   }
   else
   {
      TimeEdit->ReadOnly = true;
      DateEdit->ReadOnly = true;
   }
   SerTXEdit->ReadOnly = true;

   bool timeOK = false;
   int tne = screenContact.time.notEntered(); // partial dtg will give +fe
   // full dtg gives -ve, none gives 0

   if (tne < 0)
   {
      dtg time(false);
      time.setDate( DateEdit->Text.c_str(), DTGDISP );
      time.setTime( TimeEdit->Text.SubString(1, 5).c_str(), DTGDISP );

      timeOK = contest->checkTime(time);
   }

//   DateEdit->Font->Assign(MinosParameters::getMinosParameters() ->getSysFont());
//   TimeEdit->Font->Assign(MinosParameters::getMinosParameters() ->getSysFont());
   if (timeOK)
   {
      DateEdit->Font->Color = clWindowText;
      TimeEdit->Font->Color = clWindowText;
   }
   else
   {
      DateEdit->Font->Color = clRed;
      TimeEdit->Font->Color = clRed;
   }

   MinosLoggerEvents::SendAfterSelectContact(catchup?0:slct, contest);
   selectField( 0 );
}
TVerdict CAppFwkStartSafeTestStepProcMonSysRestart::doTestStepL()
	{
	
#ifdef __WINSCW__
	ASSERT(0);
#endif	

	CActiveScheduler* sched = new(ELeave) CActiveScheduler;
	CleanupStack::PushL(sched);
	CActiveScheduler::Install(sched);	
	
	iNotifier = CSaveNotifier::NewL(*this);

	CStartSafe* startSafe = CStartSafe::NewL();	
	CleanupStack::PushL( startSafe );

	CStartupProperties* prop = CStartupProperties::NewLC();
	prop->SetFileParamsL(KTestProcGood, KNullDesC);	
	prop->SetStartMethod(EWaitForStart);
	prop->SetMonitored(ETrue);
	prop->SetRecoveryParams(ERestartOS, 0);
	
	TInt tried;
	RProcess proc;
	CleanupClosePushL(proc);
	TRAPD(err, startSafe->StartAndMonitorL(*prop, proc, tried));
	TEST(KErrNone == err);
	CleanupStack::Pop(&proc);
	CleanupStack::PopAndDestroy(prop);
	CleanupStack::PopAndDestroy(startSafe);
	INFO_PRINTF1(_L("Process monitoring setup with TRecoveryMethod=ERestartOS"));

	proc.Kill(KErrNone);
	proc.Close();
	
	TTime init;
	init.UniversalTime();
	INFO_PRINTF4( _L("Process killed at time %d:%d.%d"), init.DateTime().Minute(), init.DateTime().Second(), init.DateTime().MicroSecond());
	INFO_PRINTF1(_L("Starting scheduler (expecting an OS restart)"));
	CActiveScheduler::Start(); //Wait for MSaveObserver callback
	
	//resume here after callback has stopped the scheduler
	TESTE(iCallbackReceived, iCallbackReceived);
	if(iCallbackReceived)
		{
		const TTimeIntervalMicroSeconds elapsedTime = iShutdownPerformed.MicroSecondsFrom(init);
		const TDateTime dt = iShutdownPerformed.DateTime();
		const TInt64 value = elapsedTime.Int64();
		INFO_PRINTF5(_L("Shutdown callback received at time %d:%d.%d (after %d microseconds)"), dt.Minute(), dt.Second(), dt.MicroSecond(), value);
		TESTE((value >= 0) && (value < 1000000), value); // within 1 second	
		}
	else
		{
		INFO_PRINTF1( _L("Restart didn't take place :-("));
		TEST(EFalse);	
		}
	
	// Now call CPowerdownClient::QueryServerPowerState() which will in turn call the method 'ServerPowerState()'
	// to stop the shutdown. This function call will cause the shutdown server in syslibs/pwrcli to cancel power off.
	INFO_PRINTF1(_L("Aborting shutdown."));
	TBool powerOff = EFalse;
	CPowerdownClient* powerdownclient = CPowerdownClient::NewL();
	CleanupStack::PushL(powerdownclient);
	TEST(KErrNone == powerdownclient->QueryServerPowerState(iNotifier,powerOff));
	TEST(powerOff);
	CleanupStack::PopAndDestroy(powerdownclient);
	
	CleanupStack::PopAndDestroy(sched);
	return TestStepResult();	
	}
void FmBkupEnginePrivate::GetRestoreInfoArray( QList<FmBkupDrivesAndOperation* > drivesAndOperationList,
        QList< FmRestoreInfo > &restoreInfoList,
        const QString& aDrive )
    {
    int targetDrive = DriverNameToNumber( aDrive );    

    restoreInfoList.clear();
    
    ///////
    iDrvAndOpList->Reset();
    iBkupCategoryList->ResetAndDestroy();
    
    for( QList<FmBkupDrivesAndOperation* >::iterator it = drivesAndOperationList.begin();
        it != drivesAndOperationList.end(); ++it )
        {
        FmBkupDrivesAndOperation* fmDrvAndOp = *it;
        TBkupDrivesAndOperation drvAndOp;
        drvAndOp.setOwnerDataType( fmDrvAndOp->ownerDataType() );
        drvAndOp.setDrvCategories( fmDrvAndOp->drvCategories() );
        iDrvAndOpList->AppendL( drvAndOp );
        }
    ////////

    CMMCScBkupOpParamsRestoreFull* params =
        CMMCScBkupOpParamsRestoreFull::NewL(
                iDrvAndOpList, FmBkupEngine::EBUCatAllSeparately );
    CleanupStack::PushL( params );

    // Get list of all archives
    RPointerArray< CMMCScBkupArchiveInfo > archives;
    TCleanupItem cleanupItem( ResetAndDestroyArchives, &archives );
    CleanupStack::PushL( cleanupItem );
    iBkupEngine->ListArchivesL(
        archives,
        params,
        AllowedDriveAttMatchMask(),
        targetDrive );

    // Fill restore info
    TInt count( archives.Count() );
//    restoreInfoList.ReserveL( count );

    for( TInt i( 0 ); i < count; ++i )
        {
        // Content
        CMMCScBkupArchiveInfo& archiveInfo( *archives[ i ] );
        
        TUint32 iContent = BkupToFmgrMask( archiveInfo.Category().iFlags );
        TTime iTime = archiveInfo.DateTime();
        TInt iDrive = archiveInfo.Drive();
        TDateTime iDateTime = iTime.DateTime();
        
        int h       = iDateTime.Hour();
        int m       = iDateTime.Minute();
        int s       = iDateTime.Second();
        int year    = iDateTime.Year();
        int month   = iDateTime.Month() + 1;
        int day     = iDateTime.Day()+1;
        QTime time( h, m, s);
        QDate date( year, month, day );
        
        QDateTime dateTime( date, time );
        dateTime = dateTime.toLocalTime();
        
        FmRestoreInfo restoreInfo( iContent, dateTime, NumberToDriverName( iDrive ) );
        restoreInfoList.append( restoreInfo );
        }

    CleanupStack::PopAndDestroy( &archives );
    CleanupStack::PopAndDestroy( params );
    }
// ---------------------------------------------------------------------------
// CLbtCleanupHandler::WriteCleanupDataToFileL
// ---------------------------------------------------------------------------
//
void CLbtCleanupHandler::WriteCleanupDataToFileL()
	{
	FUNC_ENTER("CLbtCleanupHandler::WriteCleanupDataToFileL");	
	
	RFs fs;
	User::LeaveIfError( fs.Connect() );
	
	CleanupClosePushL( fs );
    
    // Obtain the file path
    TFileName file;
    
    // Gets the path in which the file can be created
    fs.SessionPath(file);

    // Create the file Directory ie the private directory of the process
    fs.MkDirAll(file);
    
    // Append the name of the file
    file.Append(KLbtAppCleanupFileName);
    
    // Open write stream to write to the file
    RFileWriteStream writeStream;
    
    // Open the file to replace the contents. If the file is not preset
    // this method will create the file
    TInt error = writeStream.Replace( fs, file, EFileWrite );    
    if( error != KErrNone )
    	{
    	ERROR("Opening of cleanup file failed with : %d", error);
    	writeStream.Close();
    	CleanupStack::PopAndDestroy(); //fs
    	User::Leave(error);
    	}
    CleanupClosePushL( writeStream );
    
    // First write the number of cleanup items
    writeStream.WriteInt16L( iCleanupItems.Count() );

	for(TInt i=0;i<iCleanupItems.Count();++i)
		{
		RArray<TLbtTriggerId>& triggers = iCleanupItems[i]->GetTriggers();
		
		// Write the trigger ids into the file
		writeStream.WriteInt16L( triggers.Count() );
		for(TInt j=0;j<triggers.Count();++j)
			{
			writeStream.WriteUint32L( triggers[j] );
			}
		
		// Write the time into the file
		const TDateTime dateTime = iCleanupItems[i]->GetTime().DateTime();
		
		// Write the year
		writeStream.WriteInt32L( dateTime.Year() );
		
		// Write the month
		writeStream.WriteInt32L( dateTime.Month() );
		
		// Write the day
		writeStream.WriteInt32L( dateTime.Day() );
		}
    
    CleanupStack::PopAndDestroy(2); //fs and writeSteam    
	}
Example #13
0
// 抓拍数据
void CALLBACK VehicleDataCallbackFuc(void *pUserData, VehicleData *pData)
{
    TForm1 *pThis = (TForm1 *)pUserData;
    if(pThis->tvConnectDev->Selected == NULL) return;

    String strIP;
    bool bFlag = false;
    PDevInfo pDev = NULL;
    TTreeNodes *nodes = pThis->tvConnectDev->Items;
    if(nodes != NULL)
    {
        for(int i = 0; i < nodes->Count; i++)
        {
            if(TreeView_GetCheckState(pThis->tvConnectDev->Handle,nodes->Item[i]->ItemId))
            {
                String strViewIP = nodes->Item[i]->Text;

                // 只显示指定抓拍的设备数据
                strIP.sprintf("%s", pData->ucDeviceIP);
                if(strIP == strViewIP)
                {
                    bFlag = true;
                    break;
                }
            }
        }
    }

     if(!bFlag) return;


     int nColor = pData->PlateColor;
     TDateTime dataTime = Now();
     SYSTEMTIME tm;
     GetSystemTime(&tm);

     String strPlate = (char *)pData->ucPlate;

     String strPath;
     String strBigFile, strCifFile, strPlateFile, strPlateNoFile;
     int iFileHandle = 0;

     // 大图
     if(pData->pucBigImage != NULL && pData->uiBigImageLen > 0)
     {
        strPath = pThis->strImagePath + strIP + "\\大图\\" + FormatDateTime("yyyymmdd", dataTime) + "\\";
        pThis->CreateDirectoryRecurrent(strPath);
        strBigFile = Format("%s%s%03d(%s).jpg", ARRAYOFCONST((strPath, dataTime.FormatString("hhmmss"), tm.wMilliseconds, strPlate)));
        iFileHandle = FileCreate(strBigFile);
        if(iFileHandle != 0)
        {
            FileWrite(iFileHandle, pData->pucBigImage, pData->uiBigImageLen);
            FileClose(iFileHandle);

            if(FileExists(strBigFile))
            {
                pThis->imgBigImg->Picture->LoadFromFile(strBigFile);
            }
        }
     }

     // CIF图
     if(pData->pucCIFImage != NULL && pData->uiCIFImageLen > 0)
     {
        strPath = pThis->strImagePath + strIP + "\\CIF图\\" + dataTime.FormatString("yyyymmdd") + "\\";
        pThis->CreateDirectoryRecurrent(strPath);
        strCifFile = Format("%s%s%03d(%s).jpg", ARRAYOFCONST((strPath, dataTime.FormatString("hhmmss"), tm.wMilliseconds, strPlate)));
        iFileHandle = FileCreate(strCifFile);
        if(iFileHandle != 0)
        {
            FileWrite(iFileHandle, pData->pucCIFImage, pData->uiCIFImageLen);
            FileClose(iFileHandle);

            if(FileExists(strCifFile))
            {
                pThis->imgCIFImg->Picture->LoadFromFile(strCifFile);
            }
        }
     }
     // 车牌图
     if(pData->pucPlateImage != NULL && pData->uiPlateImageLen > 0)
     {
        strPath = pThis->strImagePath + strIP + "\\车牌图\\" + dataTime.FormatString("yyyymmdd") + "\\";
        pThis->CreateDirectoryRecurrent(strPath);
        strPlateFile = Format("%s%s%03d(%s).jpg", ARRAYOFCONST((strPath, dataTime.FormatString("hhmmss"), tm.wMilliseconds, strPlate)));
        iFileHandle = FileCreate(strPlateFile);
        if(iFileHandle != 0)
        {
            FileWrite(iFileHandle, pData->pucPlateImage, pData->uiPlateImageLen);
            FileClose(iFileHandle);
        }

        if(FileExists(strPlateFile))
        {
            pThis->imgPlateImg->Picture->LoadFromFile(strPlateFile);
        }
     }

     // 车牌号码
     pThis->ShowPlate(strPlate, nColor);

}
//---------------------------------------------------------------------------
// Check to see if SelfImage is up-to-date - notify the user if it isn't
//
void CheckVersion(void) {

  TDateTime *dtLastCheck = NULL;
  char *filename = NULL;
  char *buffer = NULL;
  char *verbuff = NULL;
  unsigned nVersionInfoSize;
  int nBuildPos;
  static AnsiString sMyVersion = "";
  static int nMyBuild = 0;
  AnsiString sCurrentVersion, sURL;
  int nCurrentBuild = 0;
  TIdHTTP *HTTP;
  DWORD nDummy;

  __ENTERFUNCTION__;

  try {
    try {
      formSelfImageNewVersionNotify = NULL;
      if (!SelfImageConfig->Values["Update Notify"]) {
        LOG(LOG_DEBUG, "Update Notify is turned off - not checking for new version.");
        goto END;  // Ugly - C++ Builder silently ignores a __finally block if a return is process from a nested try.
      }  // if (!SelfImageConfig->Values["Update Notify"])

      if (String(SelfImageConfig->Values["Last Version Check"]).IsEmpty())
        SelfImageConfig->Values["Last Version Check"] = (Now()-1).DateTimeString();
      dtLastCheck = new TDateTime(String(SelfImageConfig->Values["Last Version Check"]));
      if (!DaysBetween(Now(), *dtLastCheck)) {
        LOG1(LOG_DEBUG, "Last new version check was performed %s - not checking again.", dtLastCheck->DateTimeString().c_str());
        goto END;  // Ugly - C++ Builder silently ignores a __finally block if a return is process from a nested try.
      }  // if (!DaysBetween(Now(), *dtLastCheck))

      SelfImageConfig->Values["Last Version Check"] = Now().DateTimeString();

      // Get this executable's version - this is a pain, so let's just do it once for each time SelfImage is instantiated
      if (!nMyBuild) {
        LOG(LOG_DEBUG, "Retrieving internal version number.");
        filename = (char *)malloc(MAXPATH);
        GetModuleFileName(HInstance, filename, MAXPATH);
        nVersionInfoSize = GetFileVersionInfoSize(filename, &nDummy);
        // These following three exceptions should never make it to the user except through the logs in a debug build.
        // Since they are only for logging, they are allowed to have text that doesn't come from the string table.
        if (!nVersionInfoSize)
          throw ESelfImageSystemError("GetFileVersionInfoSize() failed: " + GetLastErrorMessage());
        buffer = (char *)malloc(nVersionInfoSize);
        if (!GetFileVersionInfo(filename, NULL, nVersionInfoSize, buffer))
          throw ESelfImageSystemError("GetFileVersionInfo() failed:" + GetLastErrorMessage());
        if (!VerQueryValue(buffer, "\\StringFileInfo\\100904E4\\FileVersion", (void **)&verbuff, NULL))
          throw ESelfImageSystemError("VerQueryValue() failed:" + GetLastErrorMessage());
        sMyVersion = verbuff;
        nBuildPos = sMyVersion.LastDelimiter(".");
        nMyBuild = sMyVersion.SubString(nBuildPos + 1, sMyVersion.Length() - nBuildPos).ToInt();
        sMyVersion = sMyVersion.SubString(1,nBuildPos-1) + " (Build " + String(nMyBuild) + ")";
        LOG1(LOG_MESSAGE, "Internal version string retrieved from resources: \"%s\".", sMyVersion.c_str());
      }  // if (sMyVersion.IsEmpty())

      // Get SelfImage's current version from the interweb - woo, this is cool
      HTTP = new TIdHTTP(NULL);
      sURL = SelfImageConfig->Values["Version URL"];
      LOG1(LOG_DEBUG, "Attempting to retrieve version string from URL \"%s\".", sURL.c_str());
      try {
        sCurrentVersion = HTTP->Get(SelfImageConfig->Values["Version URL"]);
        nBuildPos = sCurrentVersion.Pos("(Build ");
        nCurrentBuild = sCurrentVersion.SubString(nBuildPos + 7, sCurrentVersion.Length() - nBuildPos - 7).ToInt();
      }
      catch (...) { sCurrentVersion = ""; }
      delete HTTP;
      #ifdef __LOGGINGENABLED__
      if (!sCurrentVersion.IsEmpty())
        LOG2(LOG_MESSAGE, "Version string \"%s\" retrieved from %s.", sCurrentVersion.c_str(), sURL.c_str())
      else
        LOG2(LOG_WARNING, "Unable to retrieve version string from URL \"%s\": %s", sURL.c_str(), HTTP->ResponseText.c_str());
      #endif

      // Compare the two...
      if (nCurrentBuild && nMyBuild < nCurrentBuild && sCurrentVersion != String(SelfImageConfig->Values["Notify Squelch"])) {
        LOG(LOG_DEBUG, "Notifying user of new version.");
        formSelfImageNewVersionNotify = new TformSelfImageNewVersionNotify(NULL, sMyVersion, sCurrentVersion);
        if (formSelfImageNewVersionNotify->ShowModal() == mrCancel)
          SelfImageConfig->Values["Notify Squelch"] = sCurrentVersion;
      }  // if (different versions)
    }  // inner try
    catch (Exception &e) {
      LOG2(LOG_ERROR, "Exception of type \"%s\" raised during new version check with message \"%s\"", String(e.ClassName()).c_str(), e.Message.c_str());
    }  // catch
  }  // outer try
  __finally {
    if (dtLastCheck)
      delete dtLastCheck;
    if (filename)
      free(filename);
    if (buffer)
      free(buffer);
    if (formSelfImageNewVersionNotify) {
      delete formSelfImageNewVersionNotify;
      formSelfImageNewVersionNotify = NULL;
    }  // if (formSelfImageNewVersionNotify)
  }
  END:
  __RETURNFUNCTION__;
}  // void CheckVersion(void)
void TAzenqosEngineUtils::MakeTimeStrFile(TTime &time,TDes& str) //str should be at least 19 in length
	{
		TDateTime date = time.DateTime();
		str.Format(KTimeStampFileFormat,date.Year()%2000,date.Month()+1,date.Day()+1,date.Hour(),date.Minute(),date.Second());
	}
Example #16
0
TBool CHttpHdrTest::CompareDate(TDateTime aDate1, TDateTime aDate2)
	{
	return ((aDate1.Year() == aDate2.Year()) &&
			(aDate1.Month() == aDate2.Month()) &&
			(aDate1.Day() == aDate2.Day()) &&
			(aDate1.Hour() == aDate2.Hour()) &&
			(aDate1.Minute() == aDate2.Minute()) &&
			(aDate1.Second() == aDate2.Second()) &&
			(aDate1.MicroSecond() == aDate2.MicroSecond()));
	}
void TAzenqosEngineUtils::ParseTimeStrMilliL(const TDesC& str,TTime &time)
	{
		TInt instrlen = str.Length();
		if(str.Length() != KTimeStampMillisecStrLen )
			User::Leave(KErrBadName);

		TDateTime date;

		TPtrC ptr(0,0);
		TInt pos=0;
		TLex lex;
		TInt val;

		//_LIT(KTimeStampMillisecFormat,"%02d%02d%02d_%02d:%02d:%02d.%03d");

		///year
		ptr.Set(str.Mid(pos,2));
		pos+=2;
		lex.Assign(ptr);
		val=0;
		User::LeaveIfError(lex.Val(val));
		val+=2000;
		User::LeaveIfError(date.SetYear(val));

		//month
		ptr.Set(str.Mid(pos,2));
		pos+=2;
		lex.Assign(ptr);
		val=0;
		User::LeaveIfError(lex.Val(val));
		if(val<1 || val > 12)//month should be at least 1 so we can set as symbian format: month-1
			User::Leave(KErrGeneral);
		val--;//Symbian format EJanuary is 0
		User::LeaveIfError(date.SetMonth((TMonth)val));

		//day
		ptr.Set(str.Mid(pos,2));
		pos+=2;
		lex.Assign(ptr);
		val=0;
		User::LeaveIfError(lex.Val(val));
		if(val<1 || val > 31)//day limit
			User::Leave(KErrGeneral);
		val--;//Symbian format EJanuary is 0
		User::LeaveIfError(date.SetDay(val));


		//skip '_'
		pos+=1;

		//HH
		ptr.Set(str.Mid(pos,2));
		pos+=2;
		lex.Assign(ptr);
		val=0;
		User::LeaveIfError(lex.Val(val));
		if(val<0 || val > 23)//0 to 23 Hrs
			User::Leave(KErrGeneral);
		User::LeaveIfError(date.SetHour(val));

		//skip ':'
		pos+=1;

		//MM
		ptr.Set(str.Mid(pos,2));
		pos+=2;
		lex.Assign(ptr);
		val=0;
		User::LeaveIfError(lex.Val(val));
		if(val<0 || val > 59)//0 to 59 mins
			User::Leave(KErrGeneral);
		User::LeaveIfError(date.SetMinute(val));

		//skip ':'
		pos+=1;

		//SS
		ptr.Set(str.Mid(pos,2));
		pos+=2;
		lex.Assign(ptr);
		val=0;
		User::LeaveIfError(lex.Val(val));
		if(val<0 || val > 59)//0 to 59 Seconds
			User::Leave(KErrGeneral);
		User::LeaveIfError(date.SetSecond(val));

		//skip '.'
		pos+=1;

		//SSS
		ptr.Set(str.Mid(pos,3));
		pos+=3;
		lex.Assign(ptr);
		val=0;
		User::LeaveIfError(lex.Val(val));
		if(val<0 || val > 999999)//0 to 999999 MicroSeconds
			User::Leave(KErrGeneral);
		User::LeaveIfError(date.SetMicroSecond(val));

		time = date;

	}
Example #18
0
TDateTime TXmlStorage::ReadDateTime(const UnicodeString & Name, const TDateTime & Default) const
{
  double Result = ReadFloat(Name, Default.GetValue());
  return TDateTime(Result);
}
 // ---------------------------------------------------------------------------
 // CGpxConverterAO::WriteItemToFile
 // Writes single trackpoint to GPX file
 // ---------------------------------------------------------------------------
void CGpxConverterAO::WriteItemToFile()
	{
	LOG("CGpxConverterAO::WriteItemToFile ,begin");
	TTime timeStamp;
	
	TPtr8 writePtr = iWriteBuf->Des();
	TPtr formatter = iFormatBuf->Des();
	
	if ( Math::IsNaN(iTempItem.iLatitude) || Math::IsNaN(iTempItem.iLongitude) )
		{
		if ( !iFixLost )
			{
			writePtr.Copy( KTagSegmentEnd );
			iGpxFile.Write( writePtr );
			iFixLost = ETrue;
			}
		}
	else
		{
		if ( iFixLost )
			{
			writePtr.Copy( KTagSegmentStart );
			iGpxFile.Write( writePtr );
			iFixLost = EFalse;
			}
		
		// write single track point
		// coordinates
		formatter.Format( KTagTrkPointStart, iTempItem.iLatitude, iTempItem.iLongitude );
		writePtr.Copy( formatter );
		iGpxFile.Write( writePtr );
		// elevation
		if ( !Math::IsNaN( iTempItem.iAltitude ))
			{
			formatter.Format( KTagElevation, iTempItem.iAltitude );
			writePtr.Copy( formatter );
			iGpxFile.Write( writePtr );
			}
		// course
		if ( !Math::IsNaN( iTempItem.iCourse ))
			{
			formatter.Format( KTagCourse, iTempItem.iCourse );
			writePtr.Copy( formatter );
			iGpxFile.Write( writePtr );
			}

		timeStamp = iTempItem.iTimeStamp;
		TDateTime datetime = timeStamp.DateTime();
		
		formatter.Format( KTagTimeStamp, datetime.Year(), datetime.Month() + 1, datetime.Day() + 1,
				datetime.Hour(), datetime.Minute(), datetime.Second() );
		writePtr.Copy( formatter );
		iGpxFile.Write( writePtr );
		
		if ( !Math::IsNaN( iTempItem.iAltitude ))
			{
			writePtr.Copy( KTagFix3D );
			iGpxFile.Write( writePtr );
			}
		else
			{
			writePtr.Copy( KTagFix2D );
			iGpxFile.Write( writePtr );
			}

		// number of satellites
		formatter.Format( KTagSatellites, iTempItem.iNumSatellites );
		writePtr.Copy( formatter );
		iGpxFile.Write( writePtr );

		// accuracy (hdop, vdop)
		if ( !Math::IsNaN( iTempItem.iHdop ))
			{
			formatter.Format( KTagHdop, iTempItem.iHdop );
			writePtr.Copy( formatter );
			iGpxFile.Write( writePtr );
			}
		if ( !Math::IsNaN( iTempItem.iVdop ))
			{
			formatter.Format( KTagVdop, iTempItem.iVdop );
			writePtr.Copy( formatter );
			iGpxFile.Write( writePtr );
			}
	
		// end track point
		writePtr.Copy( KTagTrkPointEnd );
		iGpxFile.Write( writePtr );
		}
	LOG("CGpxConverterAO::WriteItemToFile ,end");
	}
Example #20
0
//hides Form2 from view when this form is shown, sets up form for certain input level
void __fastcall TForm3::FormShow(TObject *Sender)
{
	//hide welcome form
	Form2->Hide();

	//set alreadyThere boolean to false
	alreadyThere = false;

	//get the current date in case accessLevel is 0
	TDateTime d = Now();
	pureDate = d;
	dateChosen = d.FormatString(L"yyyy-mm-dd");

	if (Form1->getAccessLevel() == 0)
	{
		//get the hotelID and query hotel_ref to find out which table to input to and which table to read from
		chooseDateImageButton->Visible = false;
		datePopupBoxLabel->Visible = false;
		calendar->Visible = false;
		String currentHotelID = Form1->getHotelID();
		inputTable = "";
		readTable = "";
		laborTable = "";
		overtimePerHour = 0;
		SQLQuery2->SQL->Text = "SELECT input_table, read_table, labor_table, Overtime_Per_Hour FROM hotel_ref WHERE hotelID = '"+currentHotelID+"';";
		SQLQuery2->Open();
		SQLQuery2->First();
		if (!SQLQuery2->Eof)
		{
			inputTable = SQLQuery2->Fields->Fields[0]->AsString;
			readTable = SQLQuery2->Fields->Fields[1]->AsString;
			laborTable = SQLQuery2->Fields->Fields[2]->AsString;
			overtimePerHour = SQLQuery2->Fields->Fields[3]->AsFloat;
		}

		//show user input screen based on input level (i.e. default or advanced)
		if (Form1->getInputLevel() == 0)
		{
			//input level is "default", query db schema
			SQLQuery2->SQL->Text = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'baldwins_hotel_data' AND TABLE_NAME = '"+inputTable+"';";

			//open query and temporarily skip first two column headings
			SQLQuery2->Open();
			SQLQuery2->First();
			SQLQuery2->Next();
			SQLQuery2->Next();

			//strings used in if for holdling column headings
			String originalHeading = "";
			String editedHeading = "";

			//set label to represent first editable column heading
			if(!SQLQuery2->Eof)
			{
				//get initial column heading without formatting (i.e. removing "_")
				originalHeading = SQLQuery2->Fields->Fields[0]->AsString;

				//replace underscores with spaces and set label
				editedHeading = StringReplace(originalHeading, "_", " ",
					TReplaceFlags() << rfReplaceAll);
				dbFieldLabel->Text = editedHeading;
				inputLabelImage->Visible=true;
				dbFieldLabel->Visible = true;
				dbFieldEdit->Visible = true;
				dbFieldEdit->Text = "";
				nextImageButton->Visible = true;

				//initially set index and size to zero
				inputObject.currentIndex = 0;
				inputObject.size = 0;
			}
		}
		//input level is "advanced" for when userAccess == 0
		else
		{
			//hide form items
			dbFieldLabel->Visible = false;
			dbFieldEdit->Visible = false;
			nextImageButton->Visible = false;

			SQLQuery2->SQL->Text = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'baldwins_hotel_data' AND TABLE_NAME = '"+inputTable+"';";

			//open query and temporarily skip first two column headings
			SQLQuery2->Open();
			SQLQuery2->First();
			SQLQuery2->Next();
			SQLQuery2->Next();
			int count = 0;
			//strings used in if for holdling column headings
			String originalHeading = "";
			String editedHeading = "";

			while (!SQLQuery2->Eof)
			{
				//get initial column heading without formatting (i.e. removing "_")
				originalHeading = SQLQuery2->Fields->Fields[0]->AsString;

				//replace underscores with spaces and set label
				editedHeading = StringReplace(originalHeading, "_", " ",
					TReplaceFlags() << rfReplaceAll);

				//show and populate displayGrid
				displayGrid->Cells[0][count] = editedHeading;
				displayGrid->Cells[1][count] = "";

				++count;
				SQLQuery2->Next();
			}

			displayGrid->RowCount = count;
			Image3->Visible=false;
			inputLabelImage->Visible=false;
			displayGrid->Visible = true;
			submitButton->Visible = true;
			Image1->Visible=true;
		}
	}
	else
	{
		//accessLevel is not 0, show date picker before progressing

		//hide uneccessary items from this page
		dbFieldLabel->Visible = false;
		dbFieldEdit->Visible = false;
		nextImageButton->Visible = false;

        //get today's date
		TDateTime d = Now();
		pureDate = d;
		dateChosen = d.FormatString(L"yyyy-mm-dd");

		chooseDateImageButton->Visible = true;
		datePopupBoxLabel->Visible = true;
		calendar->Visible = true;
	}
}
Example #21
0
//---------------------------------------------------------------------------
void __fastcall TFormDLL::FormShow(TObject *Sender)
{
  TDateTime dt;
  DateTimePickerOplata->Date=dt.CurrentDate();
}
Example #22
0
void __fastcall TReportForm::ToolButton3Click(TObject *Sender)
{

  Variant WordApp, WordSel, WordDoc, EmptyParam, table, cell, range;
  TDateTime dtReport = Date();
  UnicodeString s=ExtractFileDir(Application->ExeName)+"\\template.doc";

  if (!FileExists(s)) {
	ShowMessage("Файл шаблона не найден");
	return;
  }

  TVirtualNode *t_root=VirtualStringTree1->RootNode->FirstChild;
  TVirtualNode *t_child;
  TReportData *data_root, *data_child;

  try {
	WordApp=GetActiveOleObject("Word.Application");
  } catch (...) {
	try {
	  WordApp=CreateOleObject("Word.Application");

	} catch (...) {
	  ShowMessage("Microsoft Word не установлен");
	  return;
	}
  }



  try {
	WordApp.OlePropertySet("Visible", false);
	WordDoc=WordApp.OlePropertyGet("Documents").OleFunction("Add", s.t_str());


//	if (WordDoc.OlePropertyGet("Bookmarks").OleFunction("Exists", "date"))
//	  ShowMessage("!");

//	WordDoc.OleFunction("GoTo", 0xFFFFFFFF, EmptyParam, EmptyParam, "date").OleFunction("Select");
	WordApp.OlePropertyGet("Selection").OleFunction("goto", 0xFFFFFFFF, EmptyParam, EmptyParam, "date");
	WordApp.OlePropertyGet("Selection").OleProcedure("TypeText", dtReport.FormatString("dd.mm.yyyy").t_str());
	WordApp.OlePropertyGet("Selection").OleFunction("goto", 0xFFFFFFFF, EmptyParam, EmptyParam, "img");
	MainForm->Chart5->CopyToClipboardMetafile(true);
	WordApp.OlePropertyGet("Selection").OleFunction("Paste");


	WordApp.OlePropertyGet("Selection").OleFunction("goto", 0xFFFFFFFF, EmptyParam, EmptyParam, "table");

//	table=WordDoc.OlePropertyGet("Tables").OleFunction("Item", 1);
//	cell=table.OleFunction("Cell", 1, 1);
//	range=cell.OlePropertyGet("Range");
//	range.OlePropertySet("Text", "F**k");
	for (size_t i=0; i < VirtualStringTree1->RootNodeCount; i++) {
	  if (!(t_root == NULL)) {
		data_root=(TReportData *)ReportForm->VirtualStringTree1->GetNodeData(t_root);
		if (!(data_root == NULL)) {
		  s=data_root->Name;
		  WordApp.OlePropertyGet("Selection").OleProcedure("TypeText", s.t_str());
		  WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
		  WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
		  WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
		  WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
		}
		else
		  continue;

		t_child=t_root->FirstChild;
		while (!(t_child == NULL))
		{
		  data_child=(TReportData *)ReportForm->VirtualStringTree1->GetNodeData(t_child);
		  if (!(data_child == NULL) && (t_child->CheckState == csCheckedNormal)) {
			s=data_child->Name;
			WordApp.OlePropertyGet("Selection").OleProcedure("TypeText", s.t_str());
			WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
			WordApp.OlePropertyGet("Selection").OleProcedure("TypeText",  FloatToStrF(data_child->pcs, ffFixed, 5, 2).t_str());
			WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
			WordApp.OlePropertyGet("Selection").OleProcedure("TypeText",  FloatToStrF(data_child->pi, ffFixed, 5, 2).t_str());
			WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
			WordApp.OlePropertyGet("Selection").OleProcedure("TypeText",  FloatToStr(data_child->angle).t_str());
			WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
		  }
		  t_child=t_child->NextSibling;
		}
		WordApp.OlePropertyGet("Selection").OlePropertyGet("Font").OlePropertySet("Bold", true);
		WordApp.OlePropertyGet("Selection").OlePropertyGet("ParagraphFormat").OlePropertySet("Alignment", 0);
		WordApp.OlePropertyGet("Selection").OleProcedure("TypeText", "Средний диаметр");
		WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
		WordApp.OlePropertyGet("Selection").OlePropertyGet("Font").OlePropertySet("Bold", false);
		WordApp.OlePropertyGet("Selection").OlePropertyGet("ParagraphFormat").OlePropertySet("Alignment", 1);
		s=FloatToStrF(data_root->pcs, ffFixed, 5, 2)+" нм.";
		WordApp.OlePropertyGet("Selection").OleProcedure("TypeText",  s.t_str());
		WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
		WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
		WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
		WordApp.OlePropertyGet("Selection").OleProcedure("TypeText", "Средний ППД");
		WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
		WordApp.OlePropertyGet("Selection").OleProcedure("TypeText",  FloatToStrF(data_root->pi, ffFixed, 5, 2).t_str());
		WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
		WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
		WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
		WordApp.OlePropertyGet("Selection").OleProcedure("TypeText", "СКО");
		WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
		s=FloatToStrF(data_root->rms, ffFixed, 5, 2)+" нм.";
		WordApp.OlePropertyGet("Selection").OleProcedure("TypeText",  s.t_str());
		WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
		WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
		if (!(i == (VirtualStringTree1->RootNodeCount-1))) {
		  WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
		  WordApp.OlePropertyGet("Selection").OlePropertyGet("Font").OlePropertySet("Bold", false);
		  WordApp.OlePropertyGet("Selection").OlePropertyGet("ParagraphFormat").OlePropertySet("Alignment", 1);
		}
	  }
	  t_root=t_root->NextSibling;
	}




	/*

	for (int i=0; i < 100; i++) {
	  WordApp.OlePropertyGet("Selection").OleProcedure("TypeText", "F**k");
	  WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
	}
	  */

	/*WordApp.OlePropertyGet("Selection").OlePropertyGet("ParagraphFormat").OlePropertySet("Alignment", 1);
	WordApp.OlePropertyGet("Selection").OlePropertyGet("Font").OlePropertySet("Bold", true);
	WordApp.OlePropertyGet("Selection").OleProcedure("TypeText", "Протокол измерений");
	WordApp.OlePropertyGet("Selection").OleProcedure("TypeParagraph");
	WordApp.OlePropertyGet("Selection").OleProcedure("TypeParagraph");
	WordApp.OlePropertyGet("Selection").OlePropertyGet("ParagraphFormat").OlePropertySet("Alignment", 0);
	WordApp.OlePropertyGet("Selection").OlePropertyGet("Font").OlePropertySet("Bold", false);
	WordApp.OlePropertyGet("Selection").OleProcedure("TypeText", dtReport.FormatString("dd.mm.yyyy").t_str());
	WordApp.OlePropertyGet("Selection").OleProcedure("TypeParagraph");
	WordApp.OlePropertyGet("Selection").OleProcedure("TypeParagraph");
	WordApp.OlePropertyGet("Tables").OlePropertySet("Add", 3, 3);
	 */
  }
  __finally{
    WordApp.OlePropertySet("Visible", true);
	WordApp=Unassigned();
  }

}
Example #23
0
// Заполнение информации по трудоёмкости по исполнителям
void TController::fillVolume(int num)
{
	if(vKHRList[num]->Works.size() != 0)
	{
		int allVolumes = 0;	// число кварталов, которые идёт КХР
		// последняя дата работы - последний срок
		TDateTime end = Model->getLastDate(vKHRList[num]);
		// необходимо определить начало работы: квартал и год
		TDateTime begin = vKHRList[num]->dtStartDate;
		Word dyear, dmonth, dday; // данные для начала работы
		Word eyear, emonth, eday; // данные по окончанию КХР
		begin.DecodeDate(&dyear, &dmonth, &dday);
		end.DecodeDate(&eyear, &emonth, &eday);
		int begQ = Model->getQuart(StrToInt(dmonth));  // квартал начала работ
		int endQ = Model->getQuart(StrToInt(emonth));  // квартал окончания работ
		int kbeg = StrToInt(dyear); // год начала работ
		int kend = StrToInt(eyear); // год окончания работ
		if(kbeg==kend)
			allVolumes = endQ - begQ + 1; // если год совпадает
		else
			allVolumes = (4-begQ+1)/*год начала*/ + 4*(kend-kbeg-1) /*промежуточные года*/ + endQ /*последний год*/ ;

		DisplayManager->showVolumeRow(vKHRList[num]->Executors.size()+1, allVolumes+2);
		int currVol = begQ;
		int currYear = kbeg;
		// заполнение названий столбцов
		for (int i=0; i < allVolumes; i++)
		{
			AnsiString data = IntToStr(currVol);
			switch(currVol)
			{
				case 1: data = "I кв. "; break;
				case 2: data = "II кв. ";break;
				case 3: data = "III кв. ";break;
				case 4: data = "IV кв. ";break;
				default: break;
			}
		  //	data+=".";
			data+=IntToStr(currYear);
			currVol++;
			if(currVol>4)
			{
				currVol=1;
				currYear++;
			}
			DisplayManager->showVolume(i+1, 0, data.c_str());
		}

		// для всех исполнителей
		for(int i=0; i<vKHRList[num]->Executors.size(); i++)
		{
			int sumVolume=0; // суммарная трудоёмкость для исполнителя
			currVol = begQ;
			currYear = kbeg;
			int id = vKHRList[num]->Executors[i]->id;
			string name = Model->execByID(vKHRList[num], id);
			DisplayManager->showVolume(0, i+1, name.c_str());
			for (int j=0; j < allVolumes; j++)
			{
				float vol = Model->getExecVolume(vKHRList[num], id, currYear, currVol);
				sumVolume+=vol;
				currVol++;
				if(currVol>4)
				{
					currVol=1;
					currYear++;
				}
				DisplayManager->showVolume(j+1, i+1, FloatToStr(vol));
			}
			DisplayManager->showVolume(allVolumes+1, i+1, FloatToStr(sumVolume));
	 	}
	 }
}
Example #24
0
void __fastcall TReportForm::ToolButton6Click(TObject *Sender)
{
	Variant ExcelApp, ExcelBooks, Book, WorkSheet, Cells, EmptyParam;
	TDateTime dtReport = Date();
	UnicodeString s=ExtractFileDir(Application->ExeName)+"\\template.xls";

	if (!FileExists(s))
	{
		ShowMessage("Файл шаблона не найден");
		return;
	}

	TVirtualNode *t_root=VirtualStringTree1->RootNode->FirstChild;
	TVirtualNode *t_child;
	TReportData *data_root, *data_child;

	try
	{
		ExcelApp = GetActiveOleObject("Excel.Application");
		ExcelBooks = ExcelApp.OlePropertyGet("WorkBooks");
	}
	catch (...)
	{
		try
		{
			ExcelApp = CreateOleObject("Excel.Application");
			ExcelBooks = ExcelApp.OlePropertyGet("WorkBooks");

		}
		catch (...)
		{
		  ShowMessage("Microsoft Excel не установлен");
		return;
		}
	}

	int i = 27;
	int j = 2;
	TFormatSettings format_settings;
	GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, format_settings);
	format_settings.DecimalSeparator = ',';

	try
	{
    	ExcelApp.OlePropertySet("Visible", false);
		Book = ExcelBooks.OleFunction("Add", s.t_str());
		WorkSheet = Book.OlePropertyGet("Worksheets").OlePropertyGet("Item", 1);
		Cells = WorkSheet.OlePropertyGet("Cells");
		Cells.OlePropertyGet("Item",4,3).OlePropertySet("Value", dtReport.FormatString("dd.mm.yyyy").t_str());
		Cells.OlePropertyGet("Item",8,1).OleProcedure("Select");
		MainForm->Chart5->CopyToClipboardMetafile(true);
		WorkSheet.OleProcedure("Paste");
		Variant shapes = WorkSheet.OlePropertyGet("Shapes").OleFunction("Item", 1);
		shapes.OleFunction("ScaleWidth", 0.9, EmptyParam, EmptyParam);
		shapes.OleFunction("ScaleHeight", 0.9, EmptyParam, EmptyParam);


		for (size_t k=0; k < VirtualStringTree1->RootNodeCount; k++)
		{
			if (t_root)
			{
				data_root = (TReportData *)ReportForm->VirtualStringTree1->GetNodeData(t_root);
				if (data_root)
				{
					s=data_root->Name;
					Cells.OlePropertyGet("Item",i,j).OlePropertySet("Value", s.t_str());
					i++;
				}


				t_child=t_root->FirstChild;
				while (t_child)
				{
					data_child=(TReportData *)ReportForm->VirtualStringTree1->GetNodeData(t_child);
					if (data_root)
					{
						s=data_child->Name;
						Cells.OlePropertyGet("Item",i,j).OlePropertySet("Value", s.t_str());
						Cells.OlePropertyGet("Item",i,j+1).OlePropertySet("Value", FloatToStrF(data_child->pcs, ffFixed, 5, 2, format_settings).t_str());
						Cells.OlePropertyGet("Item",i,j+2).OlePropertySet("Value", FloatToStrF(data_child->pi, ffFixed, 5, 2, format_settings).t_str());
						Cells.OlePropertyGet("Item",i,j+3).OlePropertySet("Value", FloatToStrF(data_child->angle, ffFixed, 5, 2,format_settings).t_str());
						i++;

					}
					t_child = t_child->NextSibling;
				}

				Cells.OlePropertyGet("Item",i,j).OlePropertySet("Value", "Средний диаметр");
				Cells.OlePropertyGet("Item",i,j).OlePropertyGet("Font").OlePropertySet("Bold", true);
				Cells.OlePropertyGet("Item",i,j+1).OlePropertySet("Value", FloatToStrF(data_root->pcs, ffFixed, 5, 2, format_settings).t_str());
				i++;
				Cells.OlePropertyGet("Item",i,j).OlePropertySet("Value", "Средний ПДД");
				Cells.OlePropertyGet("Item",i,j).OlePropertyGet("Font").OlePropertySet("Bold", true);
				Cells.OlePropertyGet("Item",i,j+1).OlePropertySet("Value", FloatToStrF(data_root->pi, ffFixed, 5, 2, format_settings).t_str());
				i++;
				Cells.OlePropertyGet("Item",i,j).OlePropertySet("Value", "СКО");
				Cells.OlePropertyGet("Item",i,j).OlePropertyGet("Font").OlePropertySet("Bold", true);
				Cells.OlePropertyGet("Item",i,j+1).OlePropertySet("Value", FloatToStrF(data_root->rms, ffFixed, 5, 2, format_settings).t_str());
				i++;
			}

			t_root=t_root->NextSibling;
		}
	}
	__finally
	{
		ExcelApp.OlePropertySet("Visible", true);
		ExcelApp=Unassigned();
	}

}
/*int old_sec=-1;
unsigned int old_kb=1000; */
void __stdcall Timer1Timer(UINT TimerID, UINT Message, DWORD dwUser, DWORD dw1, DWORD dw2)
{
 // раз в секунду запись в архив
 static char       NameCurDir[255];
 static AnsiString TekDir         ;
 static bool       first=true     ;
 int               handle_file    ;
 AnsiString ARHIV = "ARHIV";
 TDateTime TD = Now();
 AnsiString YEAR  = TD.FormatString("yyyy");
 AnsiString MON   = TD.FormatString("mm")  ;
 AnsiString DAT   = TD.FormatString("dd")  ;
 AnsiString HOUR  = TD.FormatString("hh")  ;
 int min = StrToInt(TD.FormatString("nn"));
 int sec = StrToInt(TD.FormatString("ss"));
 double tim = TD.Val;
 /*if ((old_sec!=-1)&&((sec-old_sec)>1)&&(old_sec!=59))
  int l=0;
 old_sec = sec;*/
 if (ActiveArhiv==NULL) return;
 if (first) // определить текущую директорию
  {
   GetCurrentDirectory(255,NameCurDir);
   TekDir    = NameCurDir;
   first     = false     ;
  }
 AnsiString  NameFile   = TekDir+"\\"+ARHIV+"\\"+YEAR+"\\"+MON+"\\"+DAT+"\\" + HOUR +".dat";
 if (!FileExists(TekDir+"\\"+ARHIV+"\\"+YEAR+"\\"+MON+"\\"+DAT+"\\" + HOUR +".dat")) // создать файл ARHIV\\XXXX\\MM\\DD\\hh - час
  {
   // Проверить наличие директории ARHIV
   if (!DirectoryExists(TekDir+"\\"+ARHIV))  if (!CreateDir(TekDir+"\\"+ARHIV)) { ActiveArhiv->Com=-10;/* FErrorDostup=true;*/return; }
   // Проверить наличие директории ARHIV\\XXXX - год
   if (!DirectoryExists(TekDir+"\\"+ARHIV+"\\"+YEAR))  if (!CreateDir(TekDir+"\\"+ARHIV+"\\"+YEAR)) { ActiveArhiv->Com=-10; /* FErrorDostup=true; */return; }
   // Проверить наличие директории ARHIV\\XXXX\\MM - месяц
   if (!DirectoryExists(TekDir+"\\"+ARHIV+"\\"+YEAR+"\\"+MON))  if (!CreateDir(TekDir+"\\"+ARHIV+"\\"+YEAR+"\\"+MON)) { ActiveArhiv->Com=-10; /*FErrorDostup=true; */return; }
   // Проверить наличие директории ARHIV\\XXXX\\MM\\DD - день
   if (!DirectoryExists(TekDir+"\\"+ARHIV+"\\"+YEAR+"\\"+MON+"\\"+DAT))  if (!CreateDir(TekDir+"\\"+ARHIV+"\\"+YEAR+"\\"+MON+"\\"+DAT)) { ActiveArhiv->Com=-10;/*FErrorDostup=true;*/return; }
   // создать файл      ARHIV\\XXXX\\MM\\DD\\hh - час

   if ((handle_file=_open(NameFile.c_str(),O_RDWR|O_BINARY|O_CREAT))>0) // создание нулевого файла
    {
     unsigned int  kb_zag = sizeof(int)*ActiveArhiv->CountTags+sizeof(int);
     unsigned char *buf;
     lseek(handle_file,0L,SEEK_SET);
     _write(handle_file,(unsigned char *)&kb_zag,sizeof(int))           ;
     _write(handle_file,(unsigned char *)ActiveArhiv->IDTags,sizeof(int)*ActiveArhiv->CountTags);
     unsigned int len_buf = ((sizeof(double)+sizeof(int))*ActiveArhiv->CountTags+sizeof(double))*3600; //  ((    значение и статус   ) *кол-во тэгов + дата и время) 60 сек * 60 мин
     buf = (unsigned char *)calloc(len_buf,sizeof(char));
     // заполнение нулями
     _write(handle_file,(unsigned char *)buf,len_buf);
     _close(handle_file);
     handle_file=-1;
     free(buf);
    }
   else { ActiveArhiv->Com = -10;/* FErrorDostup = true; */return; }
  }
 if ((handle_file=_open(NameFile.c_str(),O_RDWR|O_CREAT|O_BINARY))>0) // Запись информации в файл
  {
   // чтение размера заголовка
   unsigned int  kb = 0L;
   unsigned long sm = min * 60 + sec;
 /*  static int old_sm=0;
   if ((sm-old_sm)>1)
    {

     int k=0;
    }
   old_sm=sm;  */
   lseek(handle_file,0L,SEEK_SET);
   _read(handle_file,&kb,sizeof(int));
  /*  int k2=0;
   else
    if ((old_kb!=kb)&&(old_kb!=1000))
     int k3=0;
   old_kb=kb;*/
   sm = kb + sm * ((sizeof(double)+sizeof(int))*ActiveArhiv->CountTags+sizeof(double));
   lseek(handle_file,sm,SEEK_SET);
   _write(handle_file,&tim,sizeof(double));//!=sizeof(double))
   /* int k4=0;   */
   /*if (ActiveArhiv->ValTags[1]<1)
    int i=0;
   if (
   */
   _write(handle_file,(unsigned char *)ActiveArhiv->ValTags,sizeof(double)*ActiveArhiv->CountTags);
   /*!=sizeof(double)*ActiveArhiv->CountTags)
    int k=0;
   if (*/
   _write(handle_file,(unsigned char *)ActiveArhiv->StatTags,sizeof(int)*ActiveArhiv->CountTags);
   /*!=sizeof(int)*ActiveArhiv->CountTags)
    int k1=0;  */
   _close(handle_file);
   handle_file=-1;
   ActiveArhiv->Com = -11; /* FErrorDostup = false;*/
  }
 else { ActiveArhiv->Com=-10;/* FErrorDostup = true;*/return; }
}
Example #26
0
	bool operator < (const TDateTime &other){
		return (GetUnixTimestamp()< other.GetUnixTimestamp());
	}
Example #27
0
//---------------------------------------------------------------------------
void TSessionLog::DoAddStartupInfo(TSessionData * Data)
{
  TGuard Guard(FCriticalSection);

  BeginUpdate();
  auto cleanup = finally([&]()
  {
    DeleteUnnecessary();
    EndUpdate();
  });
  {
    #define ADF(S, ...) DoAdd(llMessage, FORMAT(S, ##__VA_ARGS__), MAKE_CALLBACK(TSessionLog::DoAddToSelf, this));
    if (Data == nullptr)
    {
      AddSeparator();
      ADF(L"NetBox %s (OS %s)", FConfiguration->GetVersionStr().c_str(), FConfiguration->GetOSVersionStr().c_str());
      std::auto_ptr<THierarchicalStorage> Storage(FConfiguration->CreateStorage(false));
      assert(Storage.get());
      ADF(L"Configuration: %s", Storage->GetSource().c_str());

      if (0)
      {
        typedef BOOL (WINAPI * TGetUserNameEx)(EXTENDED_NAME_FORMAT NameFormat, LPWSTR lpNameBuffer, PULONG nSize);
        HINSTANCE Secur32 = LoadLibrary(L"secur32.dll");
        TGetUserNameEx GetUserNameEx =
          (Secur32 != nullptr) ? reinterpret_cast<TGetUserNameEx>(GetProcAddress(Secur32, "GetUserNameExW")) : nullptr;
        wchar_t UserName[UNLEN + 1];
        unsigned long UserNameSize = LENOF(UserName);
        if ((GetUserNameEx == nullptr) || !GetUserNameEx(NameSamCompatible, (LPWSTR)UserName, &UserNameSize))
        {
          wcscpy(UserName, L"<Failed to retrieve username>");
        }
        ADF(L"Local account: %s", UserName);
      }
      unsigned short Y, M, D, H, N, S, MS;
      TDateTime DateTime = Now();
      DateTime.DecodeDate(Y, M, D);
      DateTime.DecodeTime(H, N, S, MS);
      UnicodeString dt = FORMAT(L"%02d.%02d.%04d %02d:%02d:%02d", D, M, Y, H, N, S);
      // ADF(L"Login time: %s", FormatDateTime(L"dddddd tt", Now()).c_str());
      ADF(L"Working directory: %s", GetCurrentDir().c_str());
      // ADF(L"Command-line: %s", CmdLine.c_str());
      // ADF(L"Time zone: %s", GetTimeZoneLogString().c_str());
      ADF(L"Login time: %s", dt.c_str());
      AddSeparator();
    }
    else
    {
      if (0)
      {
        ADF(L"Session name: %s (%s)", Data->GetSessionName().c_str(), Data->GetSource().c_str());
      }
      ADF(L"Host name: %s (Port: %d)", Data->GetHostNameExpanded().c_str(), Data->GetPortNumber());
      if (0)
      {
        ADF(L"User name: %s (Password: %s, Key file: %s)",
          Data->GetUserNameExpanded().c_str(), BooleanToEngStr(!Data->GetPassword().IsEmpty()).c_str(),
           BooleanToEngStr(!Data->GetPublicKeyFile().IsEmpty()).c_str())
      }
      ADF(L"Tunnel: %s", BooleanToEngStr(Data->GetTunnel()).c_str());
      if (Data->GetTunnel())
      {
        ADF(L"Tunnel: Host name: %s (Port: %d)", Data->GetTunnelHostName().c_str(), Data->GetTunnelPortNumber());
        if (0)
        {
          ADF(L"Tunnel: User name: %s (Password: %s, Key file: %s)",
            Data->GetTunnelUserName().c_str(), BooleanToEngStr(!Data->GetTunnelPassword().IsEmpty()).c_str(),
             BooleanToEngStr(!Data->GetTunnelPublicKeyFile().IsEmpty()).c_str());
            ADF(L"Tunnel: Local port number: %d", Data->GetTunnelLocalPortNumber());
        }
      }
      ADF(L"Transfer Protocol: %s", Data->GetFSProtocolStr().c_str());
      ADF(L"Code Page: %d", Data->GetCodePageAsNumber());
      wchar_t * PingTypes = L"-NC";
      TPingType PingType;
      intptr_t PingInterval;
      if (Data->GetFSProtocol() == fsFTP)
      {
        PingType = Data->GetFtpPingType();
        PingInterval = Data->GetFtpPingInterval();
      }
      else
      {
        PingType = Data->GetPingType();
        PingInterval = Data->GetPingInterval();
      }
      ADF(L"Ping type: %s, Ping interval: %d sec; Timeout: %d sec",
        UnicodeString(PingTypes[PingType]).c_str(), PingInterval, Data->GetTimeout());
      ADF(L"Proxy: %s%s", ProxyMethodList[Data->GetProxyMethod()],
        Data->GetProxyMethod() == pmSystem ?
          ::Format(L" (%s)", ProxyMethodList[Data->GetActualProxyMethod()]).c_str() :
          L"")
      if (Data->GetProxyMethod() != ::pmNone)
      {
        ADF(L"HostName: %s (Port: %d); Username: %s; Passwd: %s",
          Data->GetProxyHost().c_str(), Data->GetProxyPort(),
           Data->GetProxyUsername().c_str(), BooleanToEngStr(!Data->GetProxyPassword().IsEmpty()).c_str());
        if (Data->GetProxyMethod() == pmTelnet)
        {
          ADF(L"Telnet command: %s", Data->GetProxyTelnetCommand().c_str());
        }
        if (Data->GetProxyMethod() == pmCmd)
        {
          ADF(L"Local command: %s", Data->GetProxyLocalCommand().c_str());
        }
      }
      wchar_t const * BugFlags = L"+-A";
      if (Data->GetUsesSsh())
      {
        ADF(L"SSH protocol version: %s; Compression: %s",
          Data->GetSshProtStr().c_str(), BooleanToEngStr(Data->GetCompression()).c_str());
        ADF(L"Bypass authentication: %s",
         BooleanToEngStr(Data->GetSshNoUserAuth()).c_str());
        ADF(L"Try agent: %s; Agent forwarding: %s; TIS/CryptoCard: %s; KI: %s; GSSAPI: %s",
           BooleanToEngStr(Data->GetTryAgent()).c_str(), BooleanToEngStr(Data->GetAgentFwd()).c_str(), BooleanToEngStr(Data->GetAuthTIS()).c_str(),
           BooleanToEngStr(Data->GetAuthKI()).c_str(), BooleanToEngStr(Data->GetAuthGSSAPI()).c_str());
        if (Data->GetAuthGSSAPI())
        {
          ADF(L"GSSAPI: Forwarding: %s; Server realm: %s",
            BooleanToEngStr(Data->GetGSSAPIFwdTGT()).c_str(), Data->GetGSSAPIServerRealm().c_str());
        }
        ADF(L"Ciphers: %s; Ssh2DES: %s",
          Data->GetCipherList().c_str(), BooleanToEngStr(Data->GetSsh2DES()).c_str());
        UnicodeString Bugs;
        for (intptr_t Index = 0; Index < BUG_COUNT; ++Index)
        {
          Bugs += UnicodeString(BugFlags[Data->GetBug(static_cast<TSshBug>(Index))])+(Index<BUG_COUNT-1?L",":L"");
        }
        ADF(L"SSH Bugs: %s", Bugs.c_str());
        ADF(L"Return code variable: %s; Lookup user groups: %c",
           Data->GetDetectReturnVar() ? UnicodeString(L"Autodetect").c_str() : Data->GetReturnVar().c_str(),
           BugFlags[Data->GetLookupUserGroups()]);
        ADF(L"Shell: %s", Data->GetShell().IsEmpty() ? UnicodeString(L"default").c_str() : Data->GetShell().c_str());
        ADF(L"EOL: %d, UTF: %d", Data->GetEOLType(), Data->GetNotUtf());
        ADF(L"Clear aliases: %s, Unset nat.vars: %s, Resolve symlinks: %s",
           BooleanToEngStr(Data->GetClearAliases()).c_str(), BooleanToEngStr(Data->GetUnsetNationalVars()).c_str(),
           BooleanToEngStr(Data->GetResolveSymlinks()).c_str());
        ADF(L"LS: %s, Ign LS warn: %s, Scp1 Comp: %s",
           Data->GetListingCommand().c_str(),
           BooleanToEngStr(Data->GetIgnoreLsWarnings()).c_str(),
           BooleanToEngStr(Data->GetScp1Compatibility()).c_str());
      }
      if (Data->GetFSProtocol() == fsSFTP)
      {
        UnicodeString Bugs;
        for (int Index = 0; Index < SFTP_BUG_COUNT; Index++)
        {
          Bugs += UnicodeString(BugFlags[Data->GetSFTPBug(static_cast<TSftpBug>(Index))])+(Index<SFTP_BUG_COUNT-1 ? L"," : L"");
        }
        ADF(L"SFTP Bugs: %s", Bugs.c_str());
        ADF(L"SFTP Server: %s", Data->GetSftpServer().IsEmpty()? UnicodeString(L"default").c_str() : Data->GetSftpServer().c_str());
      }
      if (Data->GetFSProtocol() == fsFTP)
      {
        UnicodeString Ftps;
        switch (Data->GetFtps())
        {
          case ftpsImplicit:
            Ftps = L"Implicit TLS/SSL";
            break;

          case ftpsExplicitSsl:
            Ftps = L"Explicit SSL";
            break;

          case ftpsExplicitTls:
            Ftps = L"Explicit TLS";
            break;

          default:
            assert(Data->GetFtps() == ftpsNone);
            Ftps = L"None";
            break;
        }
        ADF(L"FTP: FTPS: %s; Passive: %s [Force IP: %c]; MLSD: %c  [List all: %c]",
           Ftps.c_str(), BooleanToEngStr(Data->GetFtpPasvMode()).c_str(),
           BugFlags[Data->GetFtpForcePasvIp()],
           BugFlags[Data->GetFtpUseMlsd()],
           BugFlags[Data->GetFtpListAll()]);
        if (Data->GetFtps() != ftpsNone)
        {
          ADF(L"Session reuse: %s", BooleanToEngStr(Data->GetSslSessionReuse()).c_str());
          ADF(L"TLS/SSL versions: %s-%s", GetTlsVersionName(Data->GetMinTlsVersion()).c_str(), GetTlsVersionName(Data->GetMaxTlsVersion()).c_str());
        }
      }
      ADF(L"Local directory: %s, Remote directory: %s, Update: %s, Cache: %s",
        (Data->GetLocalDirectory().IsEmpty() ? UnicodeString(L"default").c_str() : Data->GetLocalDirectory().c_str()),
         (Data->GetRemoteDirectory().IsEmpty() ? UnicodeString(L"home").c_str() : Data->GetRemoteDirectory().c_str()),
         BooleanToEngStr(Data->GetUpdateDirectories()).c_str(),
         BooleanToEngStr(Data->GetCacheDirectories()).c_str());
      ADF(L"Cache directory changes: %s, Permanent: %s",
         BooleanToEngStr(Data->GetCacheDirectoryChanges()).c_str(),
         BooleanToEngStr(Data->GetPreserveDirectoryChanges()).c_str());
      intptr_t TimeDifferenceMin = TimeToMinutes(Data->GetTimeDifference());
      ADF(L"DST mode: %d; Timezone offset: %dh %dm", static_cast<int>(Data->GetDSTMode()), (TimeDifferenceMin / MinsPerHour), (TimeDifferenceMin % MinsPerHour));

      if (Data->GetFSProtocol() == fsWebDAV)
      {
        ADF(L"Compression: %s",
          BooleanToEngStr(Data->GetCompression()).c_str());
      }

      AddSeparator();
    }

    #undef ADF
  }
}
Example #28
0
void CAzqBtGPSReader::RunL()
{

	iCallbackTimer->Cancel();

	switch(iState)
	{
		case ENoState:
		break;

		case EInquiringDevices:
			{
				if( iStatus !=KErrNone)
					{
						iHostResolver.Close();

						if(iStatus == KErrHostResNoMoreResults)
							{

	    							{
	    							iGPSData.Reset();
									_LIT(KGPSStateUpdate,"BT GPS Search finished...");
									iObserver.OnGPSStateUpdate(KGPSStateUpdate,iGPSData );
										}

						    //choose and connect to BT GPS modules
						    if(iBtGPSArray.Count()>0)
						    	{
						    		User::LeaveIfError(iSendingSocket.Open(iSocketServer,RFCOMM));
		    						TBTSockAddr address;
		    						address.SetBTAddr(iBtGPSArray[0]);
		    						// GPS devices usually use port 1 as data channel
		    						// so we don't have to query it
		    						address.SetPort(1);

		    							{
		    							iGPSData.Reset();
		    							iState = EConnecting;
										_LIT(KGPSStateUpdate,"Trying to connect to first device");
										iObserver.OnGPSStateUpdate(KGPSStateUpdate,iGPSData );
											}


		    						iSendingSocket.Connect(address, iStatus);
		    						SetActive();
		    						ResetBtTimer();

						    	}
						    else
						    	{

						    		{
						    		iGPSData.Reset();
						    		iState = ENoState;
									_LIT(KGPSStateUpdate,"No BT GPS. Retry press 9");
									iObserver.OnGPSStateUpdate(KGPSStateUpdate,iGPSData );
									}


						    	}

							}
						else
							{
								{
								iGPSData.Reset();
								iState = ENoState;
								_LIT(KGPSStateUpdate,"Search failed. Retry press 9");
								iObserver.OnGPSStateUpdate(KGPSStateUpdate,iGPSData );
									}



							}
					}
				else
					{

					TInquirySockAddr &addr = TInquirySockAddr::Cast(iNameEntry().iAddr);

					if(addr.MajorClassOfDevice() == KBtGPSMajorClass)
						{
							//add to array...
							iBtGPSArray.AppendL(addr.BTAddr());

								{
								iGPSData.Reset();
							_LIT(KGPSStateUpdate,"Found %d BT GPS, Searching...");
							TBuf<128> buf;
							buf.Format(KGPSStateUpdate, iBtGPSArray.Count());
							iObserver.OnGPSStateUpdate(buf,iGPSData );
								}
						}

					    ///////////get next device
						iState = EInquiringDevices;
						iHostResolver.Next(iNameEntry, iStatus);
						SetActive();
						ResetBtTimer();
						///////////////////////////////////
					}
			}
		break;

		case EConnecting:
			{
				if( iStatus !=KErrNone)
					{
						//remove previous device from array
						if(iBtGPSArray.Count()>0)
							{
							iBtGPSArray.Remove(0);
							}

						//if more gps devices remaining to try
						if(iBtGPSArray.Count()>0)
							{
								//socket alraedy opened...

								TBTSockAddr address;
								address.SetBTAddr(iBtGPSArray[0]);
								// GPS devices usually use port 1 as data channel
								// so we don't have to query it
								address.SetPort(1);

								iState = EConnecting;

									{
									iGPSData.Reset();
									_LIT(KGPSStateUpdate,"Connecting next device");
									iObserver.OnGPSStateUpdate(KGPSStateUpdate,iGPSData );
										}

								iSendingSocket.Connect(address, iStatus);
								SetActive();
								ResetBtTimer();
							}
						else//finished list
							{
								{
								iGPSData.Reset();
								iState = ENoState;

								_LIT(KGPSStateUpdate,"Connect GPS failed. Retry press 9");
								iObserver.OnGPSStateUpdate(KGPSStateUpdate,iGPSData );
									}

								iSendingSocket.Close();
							}
					}
				else
					{
						iState = EReading;
							{
							_LIT(KGPSStateUpdate,"Reading GPS data...");
							iObserver.OnGPSStateUpdate(KGPSStateUpdate,iGPSData );
								}
						iWaitGPSReadyRetry = 0; //only related if iSyncTimeWhenValid is ETrue
						line.Zero();
						iLineHeadReceivedTime = 0;//just to make sure it's fresh
						iSendingSocket.RecvOneOrMore(data, 0, iStatus, iReadDataLength);
						SetActive();
						ResetBtTimer();
					}
			}
		break;

		case EReading:
			{

				if( iStatus !=KErrNone)
					{

						{
						iGPSData.Reset();
						iState = ENoState;

						_LIT(KGPSStateUpdate,"Read GPS failed. Retry press 9");
						iObserver.OnGPSStateUpdate(KGPSStateUpdate,iGPSData );
							}


						iSendingSocket.Close();
						return;
					}

				iState = EReadComplete;

				iGPSData.Reset();//prepare for new data

				int rpos = 0;

				while ((rpos = data.Locate('\r')) != KErrNotFound)
				{
					TPtrC8 leftr(0,0);
					leftr.Set(data.Left(rpos));

					TInt leftrlen = leftr.Length();

					if(leftrlen + line.Length() < line.MaxLength())
						{
							if(line.Length()==0)
								iLineHeadReceivedTime.HomeTime();
							line.Append(leftr);
						}
					else
					{
						line.Zero();

						if(leftrlen + line.Length() < line.MaxLength())
							{
								//if(line.Length()==0) sure it is, see above lines
									iLineHeadReceivedTime.HomeTime();
								line.Append(leftr);
							}
					}

					if(rpos+1<data.Length())
						{
							data.Copy(data.Mid(rpos+1));

							if(data[0] == '\n')
								data.Delete(0,1);
						}
					else
						{
							data.Zero();
						}



					TGPSData gpsdata;
					TTimeIntervalMicroSeconds proctime;

					if(iLineHeadReceivedTime == TTime(0))//just in case...
						{
						iLineHeadReceivedTime.HomeTime();
						CAknWarningNote* informationNote = new (ELeave) CAknWarningNote(ETrue);
						//informationNote->SetTimeout(CAknNoteDialog::EShortTimeout);
						_LIT(KConfirmText,"Warning: No read-offset time correction");
						informationNote->ExecuteLD(KConfirmText);
						}

					if(gpsdata.ParseGPSInput(line,iLineHeadReceivedTime,proctime))
					{


						if((gpsdata.POS_STAT.Length() == 0) || (gpsdata.POS_STAT.Length()>0 && gpsdata.POS_STAT[0]!='A'))//if data NOT valid
							{
							///////////////BEGIN parsed but NOT valid data

							if(iSyncTimeWhenValid)//if the NetMonview is in the "Awaiting Fresh GPS Params State for the first time of session - needs time sync"
								{
									if(iWaitGPSReadyRetry>=KMaxWaitGPSReadyRetries)
									{
										//max retries finished, notify as in EReadcomplete state as set by above
										_LIT(KGPSStateUpdate,"GPS Connected but Not Ready");
										iObserver.OnGPSStateUpdate(KGPSStateUpdate,iGPSData );
										iSyncTimeWhenValid = EFalse;
									}
									else
									{
									//don't notify as in EReadcomplete state yet...
									iState = EReading;
									iWaitGPSReadyRetry++;
									TBuf<64> buf;
									_LIT(KGPSStateUpdateFormat,"GPS NotReady: TimeSync retry %d/%d");

									buf.Format(KGPSStateUpdateFormat,iWaitGPSReadyRetry,KMaxWaitGPSReadyRetries);

									iObserver.OnGPSStateUpdate(buf,iGPSData );
									}
								}
							else
								{
									_LIT(KGPSStateUpdate,"GPS Connected but Not Ready");
									iObserver.OnGPSStateUpdate(KGPSStateUpdate,iGPSData );
								}




									//latdeg = londeg = latmin = lonmin = latsec = lonsec = 0;
									line.Zero();


									if(data.Length()>0)
										{
											if(line.Length() + data.Length() < line.MaxLength())
												{
												iLineHeadReceivedTime.HomeTime();
												line.Append(data);
												}
											else
												{
													line.Zero();
													if(line.Length() + data.Length() < line.MaxLength())
														{
														//line is zero len from line.Zero() above
														iLineHeadReceivedTime.HomeTime();
														line.Append(data);
														}
												}
										}

									data.Zero();

									iState = EReading;
									iSendingSocket.RecvOneOrMore(data, 0, iStatus, iReadDataLength);
									SetActive();
									ResetBtTimer();
									return;
									///////////////END not valid
								}

						////////// boyond here is the VALID case


						////////////set device's UTC time
						if(iSyncTimeWhenValid)
							{

										TTime devTime;
										devTime.HomeTime();
										TDateTime dt = devTime.DateTime();


										if(gpsdata.POS_UTC.Length() < 6 || gpsdata.DATE.Length() < 6)
										{
											//line not ready/full... do nothing
										}
										else
										{

											//All NMEA chars are ASCII

											dt.SetHour((gpsdata.POS_UTC[0]-48)*10+(gpsdata.POS_UTC[1]-48));
											dt.SetMinute((gpsdata.POS_UTC[2]-48)*10+(gpsdata.POS_UTC[3]-48));
											dt.SetSecond((gpsdata.POS_UTC[4]-48)*10+(gpsdata.POS_UTC[5]-48));


											dt.SetDay((gpsdata.DATE[0]-48)*10+(gpsdata.DATE[1]-48) -1);

											dt.SetMonth(TMonth((gpsdata.DATE[2]-48)*10+(gpsdata.DATE[3]-48) -1));

											dt.SetYear((gpsdata.DATE[4]-48)*10+(gpsdata.DATE[5]-48)+KY2K);



											if(gpsdata.POS_UTC.Length()>9 && gpsdata.POS_UTC.Find(_L8("."))>0)
											{
												dt.SetMicroSecond((gpsdata.POS_UTC[7]-48)*KONEHUNDREDTHOUSAND+(gpsdata.POS_UTC[8]-48)*KTENTHOUSAND+(gpsdata.POS_UTC[9]-48)*1000);
											}

											devTime = dt;
											devTime += proctime;
#ifdef EKA2
											User::SetUTCTime(devTime);
#else
											//TODO: detect timezone and add accordingly
											TTime hometime(devTime);
											hometime += TTimeIntervalHours(7);
											User::SetHomeTime(hometime);
#endif


											iSyncTimeWhenValid = EFalse;

											CAknConfirmationNote* informationNote = new (ELeave) CAknConfirmationNote(EFalse);
											//informationNote->SetTimeout(CAknNoteDialog::EShortTimeout);
											_LIT(KConfirmText,"GPS TimeSync Successful");
											informationNote->ExecuteLD(KConfirmText);
											//TODO: report to scheduler that device time has changed? OR let scheduler detect device time change?


										}

							}
						/////////////////////////

							//SET LAT LON values...
							TBuf<1> ref;


							if(gpsdata.LAT.Length() < iGPSData.iLat.MaxLength()   && gpsdata.LAT_REF.Length()==1)
								{
							iGPSData.iLat.Copy(gpsdata.LAT);
							ref.Zero();
							ref.Copy(gpsdata.LAT_REF);
							iGPSData.iLat+=ref;
								}

							if(gpsdata.LON.Length() < iGPSData.iLon.MaxLength() && gpsdata.LON_REF.Length()==1)
								{
							iGPSData.iLon.Copy(gpsdata.LON);
							ref.Zero();
							ref.Copy(gpsdata.LON_REF);
							iGPSData.iLon+=ref;
								}






						_LIT(KGPSStateUpdate,"Connected to GPS");
						iObserver.OnGPSStateUpdate(KGPSStateUpdate,iGPSData );


					}//END if gps parsed


					line.Zero();
				}


				if(data.Length()>0)
					{
						if(line.Length() + data.Length() < line.MaxLength())
							{
								if(line.Length()==0) //if not appending data to previous line
									iLineHeadReceivedTime.HomeTime();
								line.Append(data);
							}
						else
							{
								line.Zero();
								if(line.Length() + data.Length() < line.MaxLength())
									{
										//if(line.Length()==0) sure it is, see above lines
											iLineHeadReceivedTime.HomeTime();
										line.Append(data);
									}
							}
					}

				data.Zero();

				iState = EReading;
				iSendingSocket.RecvOneOrMore(data, 0, iStatus, iReadDataLength);
				SetActive();
				ResetBtTimer();
			}
			break;
	}


}
//---------------------------------------------------------------------------
__fastcall TCalendarForm::TCalendarForm( TComponent* Owner )
      : TForm( Owner ), vhf(2000)
{
   TDateTime tnow = TDateTime::CurrentDateTime();
   YearEdit->Text = tnow.FormatString("yyyy");
}
Example #30
0
void CTzUserDataTest::CreateUserTzBasedOnLondonRuleL(RTz& aRTz, TTest aWhatToTest)
	{
	test.Next(_L("Test Creation user-defined time zone based on London rules"));
	//create a new rule which doesn't have DST saving.
	TTime start (TDateTime(2010, ESeptember, 0, 0, 0, 0, 0));
	TInt year = start.DateTime().Year();
	TMonth month = start.DateTime().Month();
	TInt day = start.DateTime().Day();
	TTzRule newrule(year, 9999, 0, 0, month,  ETzFixedDate, day,  0, ETzWallTimeReference, 120);

	//Get the existing london rule
	_LIT8(KTimeNone, "Europe/London");
	
	CTzId* londonId = CTzId::NewL(KTimeNone());
	CleanupStack::PushL(londonId);
	CTzRules* userrule = aRTz.GetTimeZoneRulesL(*londonId, 0, 9999, ETzUtcTimeReference);
	CleanupStack::PopAndDestroy(londonId); 

	//Use London rule to create a new user-defined rule
	TInt count = userrule->Count();

	//Since the last two rules (TTzRule objects one for summer rule one for winter rule) in existing database covers the years in which a new rule starts.
	//The client has to amend the ending years of those two rules before adding a new rule.
	//We set the ending year for last two rules to 2009 since the new rule starts on 2010

	TTzRule lastRule = (*userrule)[count-1];
	TDateTime dateTimeLast = lastRule.iTo.iTime.DateTime();
	dateTimeLast.SetYear(2009);
	lastRule.iTo.iTime = dateTimeLast;

	TTzRule lastSecondRule = (*userrule)[count-2];
	TDateTime dateTimeLastSecond = lastSecondRule.iTo.iTime.DateTime();
	dateTimeLastSecond.SetYear(2009);
	lastSecondRule.iTo.iTime = dateTimeLastSecond;
		
	CleanupStack::PushL(userrule);
	//Remove last two existing rules
	userrule->RemoveRule(count-1);
	userrule->RemoveRule(count-2);
	
	//Add two rules whoes ending years have been amended
	userrule->AddRuleL(lastRule);
	userrule->AddRuleL(lastSecondRule);
	
	//Add the new rule
	userrule->AddRuleL(newrule);
	//userrule->AddRuleL(newrule);//add the new rule which doesn't have DST
	
	CTzUserNames* newRuleNames = CreateUserDefinedTzNamesLC();
	CTzId* id = iUserData->CreateL(*userrule, *newRuleNames);
	CleanupStack::PushL(id);
	iTzIds.AppendL(id);
	CleanupStack::Pop(id);
	CheckTimeZoneL(*id, *userrule, *newRuleNames);
	CleanupStack::PopAndDestroy(newRuleNames);
		
	RArray<TTime> timesOn;
	CleanupClosePushL(timesOn);
	RArray<TTime> timesOff;
	CleanupClosePushL(timesOff);
	
	// Check UTC offset and DST.
	TTime check = TDateTime(1998, ESeptember, 0, 0, 0, 0, 0); 
	timesOn.AppendL(check);
	check = TDateTime(2005, ESeptember, 0, 0, 0, 0, 0);
	timesOn.AppendL(check);	
	check = TDateTime(2009, ESeptember, 0, 0, 0, 0, 0);
	timesOn.AppendL(check);

	check = TDateTime(2010, ESeptember, 0, 3, 0, 0, 0); 
	timesOff.AppendL(check);
	check = TDateTime(2015, ESeptember, 0, 3, 0, 0, 0);
	timesOff.AppendL(check);	
	check = TDateTime(2020, ESeptember, 0, 3, 0, 0, 0);
	timesOff.AppendL(check);

	if(aWhatToTest==ETimeConversion)
		{
		TestUtcOffsetL(*id,*userrule, timesOn, 60, aRTz);
		TestUtcOffsetL(*id,*userrule, timesOff, 0, aRTz);
		}
	else if(aWhatToTest==EDayLightSave)
		{
		TestDaylightSavingStateL(*id, timesOn, ETrue, aRTz);
		TestDaylightSavingStateL(*id, timesOff, EFalse, aRTz);
		}
	
	CleanupStack::PopAndDestroy(3, userrule);	
	}