// -----------------------------------------------------------------------------
// CPIMAgnToDoAdapter::ReadDateFieldsL
// (other items were commented in a header)
// -----------------------------------------------------------------------------
//
void CPIMAgnToDoAdapter::ReadDateFieldsL(MPIMItemData& aData, CCalEntry& aEntry)
{
    JELOG2(EPim);
    TTime nullTime = Time::NullTTime();
    // The Agenda todo entry end field is the due date
    TTime due(aEntry.EndTimeL().TimeLocalL());
    if (due != nullTime)
    {
        // Set due to the PIM API specific due date, in this case, the start of date
        // Note that PIM API uses times as UTC times so the due date must be in
        // correct format. Previously requested as local time -> do not change
        TPIMDate pimDueDate(StartOfDay(due));
        // Date must be converted UTC time because acquired as local above
        ConvertTimeL(pimDueDate, EPIMDateUTC);
        TPIMFieldData dueFieldData(EPIMToDoDue, KPIMAttrNone, pimDueDate);
        aData.AddValueL(dueFieldData);

        // Get alarm. Ownership is transferred to the caller. Alarm cannot be set
        // if the due date is not set because the calculation is done as an offset
        // from the ToDo due date.
        CCalAlarm* calAlarm = aEntry.AlarmL();
        if (calAlarm)
        {
            TTimeIntervalMinutes nativeValue = calAlarm->TimeOffset();
            // The alarm is not needed anymore so it can be deleted
            delete calAlarm;
            calAlarm = NULL;
            // Change the time to the start of the due date
            TTime startOfDayLocal(StartOfDay(due));
            // Calculate the difference from the start of due date and start time including
            // the original alarm offset which was previously read
            TTimeIntervalMinutes temp(0);
            User::LeaveIfError(startOfDayLocal.MinutesFrom(due, temp));
            // Since it is not possible to substract TTimeIntervalMinutes
            // from TTime (probably a Symbian error), the difference has
            // to be calculated using the following way...
            TInt alarm = (nativeValue.Int() + temp.Int()) * KPIMSecondsInMinute;
            // Add alarm value to the item
            TPIMFieldData fieldData(EPIMToDoExtAlarm, EPIMFieldInt,
                                    KPIMAttrNone, alarm);
            // Add value to the PIM item data
            aData.AddValueL(fieldData);
        }
    }

    // Completion date. If the item has a completion date, the item is then completed
    // and completed flag is set to true in PIM API. Null time if not crossed out.
    TTime completed = aEntry.CompletedTimeL().TimeUtcL();
    if (completed != nullTime)
    {
        TPIMFieldData dateData(EPIMToDoCompletionDate, KPIMAttrNone, completed);
        aData.AddValueL(dateData);
        // Note that boolean and integer fields must be identified in the constructor
        TPIMFieldData flag(EPIMToDoCompleted, EPIMFieldBoolean, KPIMAttrNone,
                           ETrue);
        aData.AddValueL(flag);
    }
}
// -----------------------------------------------------------------------------
// CPIMAgnEventAdapter::SetAlarmToEntryL
// Sets the native entry alarm field.
// -----------------------------------------------------------------------------
//
void CPIMAgnEventAdapter::SetAlarmToEntryL(CCalEntry& aEntry, const TInt aValue) const
{
    JELOG2(EPim);
    TTimeIntervalMinutes offMin(aValue / KPIMSecondsInMinute);
    CCalAlarm* agnAlarm = CCalAlarm::NewL();
    agnAlarm->SetTimeOffset(offMin);

    CleanupStack::PushL(agnAlarm);
    aEntry.SetAlarmL(agnAlarm);
    CleanupStack::PopAndDestroy(agnAlarm);
}
/**
* Test the alarm properties of the entry that has alarm content.
*
* @param aEntry The calendar entry to test.
* @param expectedContent The expected content in aEntry.
* @param expectedMimeType The expected mime type in aEntry.
*/	
void CCalAlarmAttachTest::TestAlarmL( CCalEntry* aEntry, 
    const TDesC8& expectedContent, const TDesC8& expectedMimeType )
	{
	CCalAlarm* almEntry = aEntry->AlarmL();
	CleanupStack::PushL(almEntry);
    test( almEntry != NULL );

	CCalContent* alarmcontent1 = almEntry->AlarmAction();
    test( alarmcontent1 != NULL );

	const TDesC8& content = alarmcontent1->Content();
    test( content == expectedContent );
	const TDesC8& mimetype = alarmcontent1->MimeType();
    test( mimetype == expectedMimeType );
    
    CleanupStack::PopAndDestroy(almEntry);
	}
// -----------------------------------------------------------------------------
// CPIMAgnEventAdapter::ReadAlarmFromAgnL
// Reads alarm offset from the native Calendar entry. In case of Anniversary,
// the offset is calculated from the midnight since native Calendar supports
// only dates in these types of entries
// -----------------------------------------------------------------------------
//
void CPIMAgnEventAdapter::ReadAlarmFromAgnL(MPIMEventItem& aItem,
        CCalEntry& aEntry)
{
    JELOG2(EPim);
    CCalAlarm* calAlarm = aEntry.AlarmL();
    // The previous function call returns NULL if there is no alarm
    // set in the item. The ownership is transferred to the caller
    // if the alarm values has been added to the item.
    if (calAlarm)
    {
        TTimeIntervalMinutes nativeValue = calAlarm->TimeOffset();
        // The alarm is not needed anymore so it can be deleted
        delete calAlarm;
        calAlarm = NULL;
        //            nativeValue.Int() );
        // Convert the alarm value based on the start time of the entry
        CCalEntry::TType entryType = aEntry.EntryTypeL();
        // Events (memos) and anniversaries do not have time in the native
        // side, therefore alarm field in those entries need to be calculated
        // from the end of the day
        if (entryType == CCalEntry::EAnniv)
        {
            TTime start(aEntry.StartTimeL().TimeLocalL());
            // Change the time to the end of the start date
            TTime startOfDayLocal(start);
            startOfDayLocal = StartOfDay(startOfDayLocal);
            // Calculate the difference from end of day and start time including
            // the original alarm offset which was previously read
            TTimeIntervalMinutes temp(0);
            User::LeaveIfError(startOfDayLocal.MinutesFrom(start, temp));
            // Since it is not possible to substract TTimeIntervalMinutes
            // from TTime (probably a Symbian error), the difference has
            // to be calculated using the following way...
            nativeValue = nativeValue.Int() + temp.Int();
        }
        TInt alarmValue = nativeValue.Int() * KPIMSecondsInMinute;
        //            alarmValue );
        // Add alarm value to the item
        TPIMFieldData fieldData(EPIMEventAlarm, EPIMFieldInt, KPIMAttrNone,
                                alarmValue);
        aItem.ItemData().AddValueL(fieldData);
    }
}
CCalAlarm* CCalAlarmAttachTest::StoreEntryWithAlarmContentLC(const TDesC8& aUid)
    {
    test.Printf(_L("Store an alarmed entry with alarm content\n"));
    // Create an attachment to the alarm.
    CCalAlarm* alarm = CCalAlarm::NewL();
    CleanupStack::PushL(alarm);
    alarm->SetTimeOffset(1);
    
    CCalContent* almContent = CCalContent::NewL();
    CleanupStack::PushL(almContent);
    // Add content and mimetype for the alarm.
    HBufC8* content = KContent().AllocLC();
    HBufC8* mimetype = KMimeType().AllocLC();
    
    almContent->SetContentL(content, mimetype, CCalContent::EDispositionInline);
    CleanupStack::Pop(mimetype);
    CleanupStack::Pop(content);    
    alarm->SetAlarmAction(almContent); // Takes ownership of almContent.
    CleanupStack::Pop(almContent); 
  
    //Create the entry with the alarm and store it
    RPointerArray<CCalEntry> entries;
    CleanupResetAndDestroyPushL(entries);
    HBufC8* guid = aUid.AllocLC();
    CCalEntry* entry = CCalEntry::NewL(CCalEntry::EEvent, guid, CCalEntry::EMethodNone, 0);
    CleanupStack::Pop(guid);
    CleanupStack::PushL(entry);
    entries.AppendL(entry);
    CleanupStack::Pop(entry);

    TCalTime calTime;
    calTime.SetTimeUtcL(TDateTime(2007,EFebruary,15, 13, 30, 0, 0));
    entry->SetStartAndEndTimeL(calTime, calTime);
    entry->SetSummaryL(KSummary());
    
    entry->SetDescriptionL(KDescription());
    entry->SetAlarmL(alarm);
    TInt entriesStored = 0;
    iTestLib->SynCGetEntryViewL().StoreL(entries, entriesStored);
    CleanupStack::PopAndDestroy(&entries);
    return alarm;
    }
void CCalAlarmAttachTest::TestDeleteAlarmWithAlarmContentL()
    {
    test.Printf(_L("Test deleting alarm from an entry \n"));
    _LIT8(KEntryUidDeleteAlarm, "DeleteAlarmUid");
    CCalAlarm* alarm = StoreEntryWithAlarmContentLC(KEntryUidDeleteAlarm());
    RPointerArray<CCalEntry> entries;
    CleanupResetAndDestroyPushL(entries);

    //Update the entry by deleting its alarm
    iTestLib->SynCGetEntryViewL().FetchL(KEntryUidDeleteAlarm(), entries);
    CCalEntry* entry = entries[0];
    entry->SetAlarmL(NULL);
    TInt entriesStored = 0;
    iTestLib->SynCGetEntryViewL().StoreL(entries, entriesStored);
    
    //Update the entry by adding an alarm but without alarm content
    entries.ResetAndDestroy();
    iTestLib->SynCGetEntryViewL().FetchL(KEntryUidDeleteAlarm(), entries);
    alarm->SetAlarmAction(NULL);
    entry = entries[0];
    entry->SetAlarmL(alarm);
    iTestLib->SynCGetEntryViewL().StoreL(entries, entriesStored);
    entries.ResetAndDestroy();

    //Fetch the entry and test the entry has an alarm but not alarm content
    iTestLib->SynCGetEntryViewL().FetchL(KEntryUidDeleteAlarm(), entries);
    CCalAlarm* almEntry = entries[0]->AlarmL();
    CleanupStack::PushL(almEntry);
    test( almEntry != NULL );

    CCalContent* alarmcontent = almEntry->AlarmAction();
    test( alarmcontent == NULL );
    CleanupStack::PopAndDestroy(almEntry);
    CleanupStack::PopAndDestroy(&entries);
    CleanupStack::PopAndDestroy(alarm);
    }
TVerdict CTestCalInterimApiRichAlarmFormatStep::doTestStepL()
	{
	CActiveScheduler* scheduler = new(ELeave)CActiveScheduler;
	CleanupStack::PushL(scheduler);  
	CActiveScheduler::Install(scheduler);

	iSession  = CCalSession::NewL();
	
	CTestCalInterimApiCallbackForRichAlarms* alarmCallback = CTestCalInterimApiCallbackForRichAlarms::NewL(this);
	CleanupStack::PushL(alarmCallback); 

	OpenSessionFileL();
	iEntryView = CCalEntryView::NewL(*iSession,*alarmCallback);
	
	CActiveScheduler::Add(alarmCallback);
	CActiveScheduler::Start();
	
	//build the CCalDataExchange object and import
	CCalDataExchange* dataExchange = CCalDataExchange::NewL(*iSession);
	CleanupStack::PushL(dataExchange); 

	//IMPORT the calendar info from a known file
	RFs fs;
	fs.Connect();
	CleanupClosePushL(fs);
	RFile inFile;
	CleanupClosePushL(inFile);
	TInt errR = inFile.Open(fs, GetFullFileName(KEntryImportFile), EFileRead);
	RFileReadStream readStream(inFile);
	CleanupClosePushL(readStream);
	
	RPointerArray<CCalEntry> secondEntryArray;
	CleanupStack::PushL(TCleanupItem(CloseAndDeleteRPtrArrayEntries, &secondEntryArray));
	secondEntryArray.Reset();
	
	INFO_PRINTF1(KImporting);
	TInt index = 0;
	for (index = 0; index < KNumEntriesInFile; index++)
		{
		dataExchange->ImportL(KUidVCalendar, readStream, secondEntryArray);
		}
	
	CleanupStack::Pop(&secondEntryArray);
	CleanupStack::PopAndDestroy(&readStream);
	CleanupStack::PopAndDestroy(&inFile);
	CleanupStack::PushL(TCleanupItem(CloseAndDeleteRPtrArrayEntries, &secondEntryArray));

	SetTestStepResult(CompareAlarmDataL(&secondEntryArray));
	
	//Test for importing from a badly formatted file
	RFile badInFile;
	CleanupClosePushL(badInFile);
	TInt baddErr = badInFile.Open(fs, GetFullFileName(KEntryBadImportFile), EFileRead);
	RFileReadStream badStream(badInFile);
	CleanupClosePushL(badStream);
	
	RPointerArray<CCalEntry> badEntryArray;
	CleanupStack::PushL(TCleanupItem(CloseAndDeleteRPtrArrayEntries, &badEntryArray));
	badEntryArray.Reset();
	
	INFO_PRINTF1(KImporting);
	TInt i = 0;
	for (i = 0; i < 1; i++)
		{
		dataExchange->ImportL(KUidVCalendar, badStream, badEntryArray);
		}
	CCalEntry* pEntry = badEntryArray[0];
	CCalAlarm* pAlarm = pEntry->AlarmL();
	if (pAlarm)
		{
		CleanupStack::PushL(pAlarm);
		CCalContent* pContent = pAlarm->AlarmAction();
		if (pContent != NULL)
			{
			ERR_PRINTF1(KUnexpectedAlarmAction);
			SetTestStepResult(EFail);
			}
		delete pContent;
		CleanupStack::PopAndDestroy(pAlarm);
		}
	CleanupStack::PopAndDestroy(&badEntryArray);
	CleanupStack::PopAndDestroy(&badStream);
	CleanupStack::PopAndDestroy(&badInFile);

	
	CleanupStack::PopAndDestroy(5 , scheduler);

	return TestStepResult();
	}
void CCalAlarmAttachTest::TestUpdateEntryHavingAlarmcontentL()
    {
    test.Printf(_L("Test updating an entry having AlarmContent \n"));
    
    //Create a Calendar entry with Alarm Content
    RPointerArray<CCalEntry> entries;
    CleanupResetAndDestroyPushL(entries);
    HBufC8* guid = KGUID1().AllocLC();
    CCalEntry* calentry = CCalEntry::NewL(CCalEntry::EEvent, guid, CCalEntry::EMethodNone, 0);
    CleanupStack::Pop(guid);
    CleanupStack::PushL(calentry);
    
    TCalTime calTime1;
    calTime1.SetTimeUtcL(TDateTime(2007,EFebruary,15, 13, 30, 0, 0));
    TCalTime calTime2;
    calTime2.SetTimeUtcL(TDateTime(2007,EFebruary,15, 14, 30, 0, 0));
    calentry->SetStartAndEndTimeL(calTime1, calTime2);
    calentry->SetSummaryL(_L("Test for Alarms"));
    CCalAlarm* alarm = CCalAlarm::NewL();
    CleanupStack::PushL(alarm);
    alarm->SetTimeOffset(1);
        
    CCalContent* almContent = CCalContent::NewL();
    CleanupStack::PushL(almContent);
    // Add content and mimetype for the alarm.
    HBufC8* content = KContent().AllocLC();
    HBufC8* mimetype = KMimeType().AllocLC();
        
    // Takes ownership of content and mimetype.
    almContent->SetContentL(content, mimetype, CCalContent::EDispositionInline);
    alarm->SetAlarmAction(almContent); // Takes ownership of almContent.
        
    calentry->SetAlarmL(alarm);
        
    CleanupStack::Pop(mimetype);
    CleanupStack::Pop(content);    
    CleanupStack::Pop(almContent); 
    CleanupStack::PopAndDestroy(alarm);

    TCalRRule rptRule;
    rptRule.SetDtStart( calTime1 );
    rptRule.SetType( TCalRRule::EYearly );
    rptRule.SetCount(5);  
    calentry->SetRRuleL(rptRule);

    entries.AppendL(calentry);
   
    // Store entry with Alarm content
    TInt entriesStored = 0;
    iTestLib->SynCGetEntryViewL().StoreL(entries, entriesStored);   
    CleanupStack::Pop(calentry);
    CleanupStack::PopAndDestroy(&entries);
    
    //Fetch stored entry and modify alarm time.
    CleanupResetAndDestroyPushL(entries);
    iTestLib->SynCGetEntryViewL().FetchL(KGUID1(), entries);
    CCalEntry* entry = entries[0];
    alarm = entry->AlarmL();
    CleanupStack::PushL(alarm);
    alarm->SetTimeOffset(1);
    entry->SetAlarmL(alarm);
    CleanupStack::PopAndDestroy(alarm);

    //Update the entry with changes.
    iTestLib->SynCGetEntryViewL().UpdateL(entries, entriesStored); 
    CleanupStack::PopAndDestroy(&entries);

    //Fetch updated entry and check if Alarm content is intact.
    CleanupResetAndDestroyPushL(entries);
    iTestLib->SynCGetEntryViewL().FetchL(KGUID1(), entries);
    TestAlarmL(entries[0], KContent(), KMimeType());
    CleanupStack::PopAndDestroy(&entries);
    }
/**
* Tests behaviour of the alarm attachments.
*
* Create 3 entries, a parent, and two child entries. The first child entry has
* an alarm attachment and stores the entry. The second child also has an 
* attachment and stores the entry. The second child's alarm attachment data 
* should overwrite the first child's alarm data.
*/
void CCalAlarmAttachTest::CreateEntriesL()
	{
    //-----------------------------------------------------------------------
	// Create parent entry with repeat rule
    //-----------------------------------------------------------------------
	RPointerArray<CCalEntry> entries;
	CleanupResetAndDestroyPushL(entries);
	
	HBufC8* guid = KGUID1().AllocLC();
	CCalEntry* parentEntry = CCalEntry::NewL(CCalEntry::EEvent, guid, CCalEntry::EMethodNone, 0);
	CleanupStack::Pop(guid);
	CleanupStack::PushL(parentEntry);
	
	TCalTime calTime1;
	calTime1.SetTimeUtcL(TDateTime(2007,EFebruary,15, 13, 30, 0, 0));
	TCalTime calTime2;
	calTime2.SetTimeUtcL(TDateTime(2007,EFebruary,15, 14, 30, 0, 0));
	parentEntry->SetStartAndEndTimeL(calTime1, calTime2);
	
	parentEntry->SetSummaryL(_L("Test for Alarms"));
	
	TCalRRule rptRule;
    rptRule.SetDtStart( calTime1 );
    rptRule.SetType( TCalRRule::EDaily );
    rptRule.SetInterval( 1 );
    rptRule.SetCount(5);
	
	parentEntry->SetRRuleL(rptRule);

	entries.AppendL(parentEntry);
   
    // Store parent entry.
	TInt entriesStored = 0;
	iTestLib->SynCGetEntryViewL().StoreL(entries, entriesStored);
	
	CleanupStack::Pop(parentEntry);
	CleanupStack::PopAndDestroy(&entries);
	
    //-----------------------------------------------------------------------
	// Create child entry with recurrence id on 17th and with alarm attachment.
    //-----------------------------------------------------------------------
	
	RPointerArray<CCalEntry> entriesToStore1;
	CleanupResetAndDestroyPushL(entriesToStore1);
	
	TCalTime recurrenceId;
	recurrenceId.SetTimeUtcL(TDateTime(2007,EFebruary,17, 13, 30, 0, 0));
	
	HBufC8* parentGuid = KGUID1().AllocLC();
	CCalEntry* childEntry1 = CCalEntry::NewL(CCalEntry::EEvent, parentGuid, 
        CCalEntry::EMethodNone, 0, recurrenceId, CalCommon::EThisOnly);
	CleanupStack::Pop(parentGuid);
	CleanupStack::PushL(childEntry1);
	
	TCalTime calTime3;
	calTime3.SetTimeUtcL(TDateTime(2007,EFebruary,21, 13, 30, 0, 0));
	TCalTime calTime4;
	calTime4.SetTimeUtcL(TDateTime(2007,EFebruary,21, 14, 30, 0, 0));
	childEntry1->SetStartAndEndTimeL(calTime3, calTime4);
	
	// Add an attachment to the alarm.
	CCalAlarm* alarm = CCalAlarm::NewL();
	CleanupStack::PushL(alarm);
	alarm->SetTimeOffset(1);
	
	CCalContent* almContent = CCalContent::NewL();
	CleanupStack::PushL(almContent);
	// Add content and mimetype for the alarm.
	_LIT8(KContent, "C:\\test.jpg");
	_LIT8(KMimeType, "mime type");
	HBufC8* content = KContent().AllocLC();
	HBufC8* mimetype = KMimeType().AllocLC();
	
    // Takes ownership of content and mimetype.
	almContent->SetContentL(content, mimetype, CCalContent::EDispositionInline);
	alarm->SetAlarmAction(almContent); // Takes ownership of almContent.
	
	childEntry1->SetAlarmL(alarm);
	
	CleanupStack::Pop(mimetype);
	CleanupStack::Pop(content);    
	CleanupStack::Pop(almContent); 
	CleanupStack::PopAndDestroy(alarm);
		
	TInt entriesStored1 = 0;
	entriesToStore1.AppendL(childEntry1);
	iTestLib->SynCGetEntryViewL().StoreL(entriesToStore1, entriesStored1);
	CleanupStack::Pop(childEntry1);
		
    // Test if the alarm details retrieved are as expected.
	CCalEntry* entry1 = entriesToStore1[0];
	TestAlarmL(entry1, KContent(), KMimeType());

    // Fetch the entry and ensure the alarm details are still as expected.
    FetchEntryL( KContent(), KMimeType() );

	CleanupStack::PopAndDestroy(&entriesToStore1);

    //-----------------------------------------------------------------------
	// Create another child entry with recurrence id and range same as above. 
    // The entry should be updated.
    //-----------------------------------------------------------------------

	RPointerArray<CCalEntry>	entriesToStore2;
	CleanupResetAndDestroyPushL(entriesToStore2);
	
	HBufC8* parentGuid1 = KGUID1().AllocLC();
	
	TCalTime recurrenceId1;
	recurrenceId1.SetTimeUtcL(TDateTime(2007,EFebruary,17, 13, 30, 0, 0));
	
	CCalEntry* childEntry2 = CCalEntry::NewL(CCalEntry::EEvent, parentGuid1, 
        CCalEntry::EMethodNone, 0, recurrenceId1, CalCommon::EThisOnly);
	CleanupStack::Pop(parentGuid1);
	CleanupStack::PushL(childEntry2);
	
	TCalTime calTime5;
	calTime5.SetTimeUtcL(TDateTime(2007,EFebruary,22, 13, 30, 0, 0));
	TCalTime calTime6;
	calTime6.SetTimeUtcL(TDateTime(2007,EFebruary,22, 14, 30, 0, 0));
	childEntry2->SetStartAndEndTimeL(calTime5, calTime6);
	
	childEntry2->SetSummaryL(_L("Update the child entry1"));
	childEntry2->SetPriorityL(2);
	
	// Add attachment to the alarm.
	CCalAlarm* alarm1 = CCalAlarm::NewL();
	CleanupStack::PushL(alarm1);
	alarm1->SetTimeOffset(1);
	
	CCalContent* almContent1 = CCalContent::NewL();
	CleanupStack::PushL(almContent1);

	// Add alarm attachment to the entry.
	_LIT8(KContent1, "C:\\longtail.jpg");
    _LIT8(KMimeType1, "mime type 2");
	HBufC8* content1 = KContent1().AllocLC();
	HBufC8* mimetype1 = KMimeType1().AllocLC();
	
	almContent1->SetContentL(content1, mimetype1, CCalContent::EDispositionInline);
	alarm1->SetAlarmAction(almContent1);
	
	childEntry2->SetAlarmL(alarm1);
	
	CleanupStack::Pop(mimetype1);
	CleanupStack::Pop(content1);
	CleanupStack::Pop(almContent1);
	CleanupStack::PopAndDestroy(alarm1);
	
	entriesToStore2.AppendL(childEntry2);
	
    // Store the child entry.
	TInt entriesStored2 = 0;
	iTestLib->SynCGetEntryViewL().StoreL(entriesToStore2, entriesStored2);

    // Store the entry again. The stream id for the alarm action will be 
    // re-used (in CAgnEntry). RAgendaServ::UpdateEntryL() will call 
    // CAgnEntry::UpdateAlarmAction() instead of StoreAlarmAction().
	iTestLib->SynCGetEntryViewL().StoreL(entriesToStore2, entriesStored2);

	CleanupStack::Pop(childEntry2);
	
	CCalEntry* entry2 = entriesToStore2[0];

	// Test if the alarm details are retrieved as expected. 
	TestAlarmL(entry2, KContent1(), KMimeType1());

    // Fetch the entry and ensure the alarm details are still as expected.
    FetchEntryL( KContent1(), KMimeType1() );

	CleanupStack::PopAndDestroy(&entriesToStore2);
	}
void CCalAlarmAttachTest::TestDeleteAlarmL()
	{
	
	CCalEntryView &view = iTestLib->SynCGetEntryViewL() ;
	CCalEntryView *calentryview = &view ;
	
	TInt num ;	

	ClearAllAlarmsL() ;	
	
	test.Printf(_L("Going to check deletion of non-snoozed alarms\n")) ;
	
	/* create repeating parent entry	*/

	HBufC8* guid = KGUID3().AllocLC(); // ownership of guid gets transferred
 	CCalEntry *entry = CCalEntry::NewL(CCalEntry::ETodo, guid, CCalEntry::EMethodNone, 0) ;
	CleanupStack::Pop(guid);	
	CleanupStack::PushL(entry) ;
	
	TTime now1;
	now1.UniversalTime();
	now1 += TTimeIntervalSeconds(30);

	TCalTime startTime ;
	TCalTime endTime ;	
	startTime.SetTimeUtcL(now1) ;
	endTime.SetTimeUtcL(now1 + TTimeIntervalSeconds(30)) ;
			
	entry->SetStartAndEndTimeL(startTime, endTime) ;

	TCalRRule rrule(TCalRRule::EDaily) ;
	rrule.SetDtStart(startTime);
	
	TCalTime endRTime ;		
	endRTime.SetTimeUtcL(now1 + TTimeIntervalDays(7)) ;	
	rrule.SetUntil(endRTime);
	rrule.SetInterval(1);	
	entry->SetRRuleL(rrule) ;

	CCalAlarm *alarm = CCalAlarm::NewL() ;
	CleanupStack::PushL(alarm) ;			
	alarm->SetTimeOffset(TTimeIntervalMinutes(0)) ;
	entry->SetAlarmL(alarm) ; //ownership does not get transferred
	
	RPointerArray<CCalEntry> entryarr ;		
	entryarr.AppendL(entry) ; //ownership does not got transferred			
	calentryview->StoreL(entryarr, num) ;
	entryarr.Close() ;		
		
	CleanupStack::PopAndDestroy(alarm) ;	
	CleanupStack::PopAndDestroy(entry) ;	
	
	/* Now let the alarm go off */
	
	RArray< TAlarmId > alarmIdArr ;
	
	iAlarmServer.GetAlarmIdListL(alarmIdArr) ;
	
	TInt cnt = alarmIdArr.Count() ;
	
	test(cnt > 0) ;
	
	TRequestStatus status = 0;
	TAlarmId alarmId = alarmIdArr[0];
	
	alarmIdArr.Close() ;
	
	test.Printf(_L("Waiting one minute for the alarm to go off...\n")) ;
	
	for(;;)
		{
		iAlarmServer.NotifyChange(status, alarmId);
		User::WaitForRequest(status);
		
		PrintEventDetails(status.Int());
		
		if	(status.Int() == EAlarmChangeEventTimerExpired)
			{			
			break; // alarm expired
			}
		}

	/* delete this entry - without snoozing */

	RPointerArray< CCalEntry > calEntryArray ;
	calentryview->FetchL(KGUID3(), calEntryArray) ;
	
	test(calEntryArray.Count() == 1) ;
	
	CCalEntry *entry1 = calEntryArray[0] ;		
	
	entry1->SetCompletedL(ETrue, startTime) ;
		
	calentryview->StoreL(calEntryArray, num) ;
	
	delete entry1 ;	
	calEntryArray.Close() ;
	
	/* now check if the alarm still exists or not */
	
	RArray< TAlarmId > alarmIdArr1 ;
	
	iAlarmServer.GetAlarmIdListL(alarmIdArr1) ;
	
	TInt cnt1 = alarmIdArr1.Count() ;
	
	test(cnt1 < cnt) ;		
	
	if (cnt1 > 0)
		{
		TAlarmId alarmId1 = alarmIdArr1[0];	
		test(alarmId != alarmId1) ;
		}			
	
	alarmIdArr1.Close() ;	
	
	ClearAllAlarmsL() ;
	
	test.Printf(_L("Checking of non snoozed alarms successful\n")) ;
	
	}
Exemplo n.º 11
0
void CTestAgendaAddAppt::AddEntriesL( void )
	{
	TInt	count=1;
	if ( !GetIntFromConfig(ConfigSection(), KCount, count) )
		count=1;

	TBuf<KMaxTestExecuteCommandLength>	tempStore;
	TInt	year;
	TInt	month;
	TInt	day;
	TInt	hour;
	TInt	minute;
	TInt	duration;
	TInt	alarm;
	TPtrC	ptrAlarmSound;
	TPtrC	ptrMessage;
	TBuf<KMaxDateStringLength> dateString;
	_LIT(KDateString,"%*E%*D%X%*N%*Y %1 %2 '%3");

	RPointerArray<CCalEntry> array;
    CleanupStack::PushL(TCleanupItem(DestroyRPointerArray, &array));

	for (TInt entry=0; entry<count && TestStepResult() == EPass; )
		{
		TTime	today;
		today.HomeTime();

		tempStore.Format(KYear(), ++entry);
		if ( !GetIntFromConfig(ConfigSection(), tempStore, year) )
			year=today.DateTime().Year();

		tempStore.Format(KMonth(), entry);
		if ( !GetIntFromConfig(ConfigSection(), tempStore, month) )
			month=today.DateTime().Month();

		tempStore.Format(KDay(), entry);
		if ( !GetIntFromConfig(ConfigSection(), tempStore, day) )
			day=today.DateTime().Day();
		else
			--day;

		tempStore.Format(KHour(), entry);
		if ( !GetIntFromConfig(ConfigSection(), tempStore, hour) )
			hour=today.DateTime().Hour();

		tempStore.Format(KMinute(), entry);
		if ( !GetIntFromConfig(ConfigSection(), tempStore, minute) )
			minute=0;

		tempStore.Format(KDuration(), entry);
		if ( !GetIntFromConfig(ConfigSection(), tempStore, duration) )
			duration=30;

		tempStore.Format(KMessage(), entry);
		GetStringFromConfig(ConfigSection(), tempStore, ptrMessage);

		TTime		startTime(TDateTime(year, TMonth(month-1+EJanuary), day, hour, minute,0,0));
		startTime.FormatL(dateString,KDateString);
	  	INFO_PRINTF2(_L("Start date is  %S"), &dateString);

		TTime		endTime = startTime + TTimeIntervalMinutes(duration);
		endTime.FormatL(dateString,KDateString);
	  	INFO_PRINTF2(_L("End date is  %S"), &dateString);

		
		HBufC8* uid = HBufC8::NewLC(255);
		TPtr8 uidP = uid->Des();
		uidP.Append(count);
		
		CCalEntry* calEntry = CCalEntry::NewL(CCalEntry::EAppt, uid, CCalEntry::EMethodNone, 0);
		
		CleanupStack::Pop(); //uid
		CleanupStack::PushL(calEntry);
		
		TCalTime calStartTime, calEndTime;
		
		calStartTime.SetTimeLocalL(startTime);
		calEndTime.SetTimeLocalL(endTime);
		
		calEntry->SetStartAndEndTimeL(calStartTime, calEndTime);
		
		tempStore.Format(KAlarm(), entry);
		if ( GetIntFromConfig(ConfigSection(), tempStore, alarm) )
			{
			TTimeIntervalMinutes	currentTime((hour*60) + minute);
			TTimeIntervalMinutes	alarmTime(currentTime.Int());
			
			CCalAlarm* calAlarm = CCalAlarm::NewL();
			CleanupStack::PushL(calAlarm);
			
			calAlarm->SetTimeOffset(alarmTime);
			
			tempStore.Format(KAlarmSound(), entry);
			if ( GetStringFromConfig(ConfigSection(), tempStore, ptrAlarmSound) )
				calAlarm->SetAlarmSoundNameL(ptrAlarmSound);
			else
				calAlarm->SetAlarmSoundNameL(_L("Bells"));
			
			calEntry->SetAlarmL(calAlarm);
			CleanupStack::PopAndDestroy(); //calAlarm
			}
		//Store in the array
		array.AppendL(calEntry);
		
		CleanupStack::Pop(); //calEntry
		}
		INFO_PRINTF1(_L("About to store appointments now"));
		TInt success(0);
		TRAPD(storeError, iCalEntryViewBase->StoreL(array, success));
		INFO_PRINTF2(_L("Store result is %d"), storeError);
		if (success != count && storeError == KErrNone)
		    {
			SetTestStepResult(EFail);
		    } 
		
		CleanupStack::PopAndDestroy(&array);
		
	}
// -----------------------------------------------------------------------------
// CPIMAgnToDoAdapter::ConvertIntToAgnL
// Makes int conversion from framework PIM item data field to To-do item field.
// -----------------------------------------------------------------------------
//
void CPIMAgnToDoAdapter::ConvertIntToAgnL(TPIMToDoField aField, // Int field to be converted
        TInt aIndex, // Index of the date field
        CCalEntry& aEntry, // The Agenda model entry typecasted to a Todo item
        const MPIMItemData& aItemData) // The PIM item to read the field from
{
    JELOG2(EPim);
    const TPIMFieldData fieldData = aItemData.ValueL(aField, aIndex);
    switch (aField)
    {
    case EPIMToDoPriority:
    {
        TInt intField = fieldData.IntegerValue();

        if ((EPIMToDoPriorityHigh <= intField) && (intField
                < EPIMToDoPriorityMedium))
        {
            aEntry.SetPriorityL(EPIMToDoNativePriorityHigh);
        }
        else if ((EPIMToDoPriorityMedium <= intField) && (intField
                 < EPIMToDoPriorityLow))
        {
            aEntry.SetPriorityL(EPIMToDoNativePriorityMedium);
        }
        else if ((EPIMToDoPriorityLow <= intField) && (intField
                 <= EPIMToDoPriorityMaxValue))
        {
            aEntry.SetPriorityL(EPIMToDoNativePriorityLow);
        }
        else
        {
            // From requirement specification: Imported to-do items with
            // priority set to zero must be mapped to the native priority
            // value Medium.
            aEntry.SetPriorityL(EPIMToDoNativePriorityMedium);
        }
        break;
    }
    case EPIMToDoClass:
    {
        CCalEntry::TReplicationStatus replicationStatus = CCalEntry::EPrivate;

        // Single value assumed
        TInt classValue = fieldData.IntegerValue();

        switch (classValue)
        {
        case EPIMToDoClassPrivate:
        {
            replicationStatus = CCalEntry::EPrivate;
            break;
        }
        case EPIMToDoClassConfidential:
        {
            replicationStatus = CCalEntry::ERestricted;
            break;
        }
        case EPIMToDoClassPublic:
        {
            replicationStatus = CCalEntry::EOpen;
            break;
        }
        default:
        {
            User::Leave(KErrArgument);
            break;
        }
        }
        aEntry.SetReplicationStatusL(replicationStatus);
        break;
    }
    case EPIMToDoExtAlarm:
    {
        CCalAlarm* agnAlarm = CCalAlarm::NewL();
        CleanupStack::PushL(agnAlarm);
        agnAlarm->SetTimeOffset(AlarmOffsetL(aItemData, aEntry));
        aEntry.SetAlarmL(agnAlarm);
        CleanupStack::PopAndDestroy(agnAlarm);
        break;
    }
    default:
    {
        // Should not happen
        __ASSERT_DEBUG(EFalse, User::Invariant());
    }
    }
}