void Timer_Calibrate::OnBnClickedOk()
{
    // TODO: 在此添加控件通知处理程序代码
    //OnOK();
    KILLTIMER;
    had_select=false;
    UpdateData(true);
    unsigned char t_time[8]= {0};
    unsigned short temp_us=0;
    temp_us=m_date_time.GetYear();
    t_time[0]=temp_us/100;
    t_time[1]=temp_us%100;
    t_time[2]=m_date_time.GetMonth();
    t_time[3]=m_date_time.GetDayOfWeek();
// 	if(t_time[3]==1)
// 		t_time[3]=6;
// 	else
// 		t_time[3]-=2;
    if(t_time[3]==1)
        t_time[3]=7;
    else
        t_time[3]-=1;

    t_time[4]=m_date_time.GetDay();
    t_time[5]=m_time_time.GetHour();
    t_time[6]=m_time_time.GetMinute();
    t_time[7]=m_time_time.GetSecond();
    Write_Multi(g_tstat_id,t_time,200,8);
    int t=_wtoi(m_time_zone.Right(m_time_zone.GetLength()-1));
    if(m_time_zone.Left(1)=="+")
        t+=12;
    else
        t=12-t;
    write_one(g_tstat_id,11,t);

    Read_Multi(g_tstat_id,machine_time,200,8,3);
    if(machine_time[1]<10)
        m_machine_time.Format(_T("   %d/%d/%d0%d %d:%d:%d"),machine_time[2],machine_time[4],machine_time[0],machine_time[1],machine_time[5],machine_time[6],machine_time[7]);
    else
        m_machine_time.Format(_T("   %d/%d/%d%d %d:%d:%d"),machine_time[2],machine_time[4],machine_time[0],machine_time[1],machine_time[5],machine_time[6],machine_time[7]);
    if(machine_time[5]>12)
        m_machine_time+=_T(" PM");
    else
        m_machine_time+=_T(" AM");

    m_NCDateCtrl.SetDate(machine_time[0]*100+machine_time[1],machine_time[2],machine_time[4]);
    m_NCTimeCtrl.SetTime(machine_time[5],machine_time[6],machine_time[7]);

    if(had_select==false)
        m_time_time=m_time_time.GetCurrentTime();
    TIME_ZONE_INFORMATION temp;
    GetTimeZoneInformation(&temp);
    m_time_zone_str=temp.StandardName;
    int i_temp=read_one(g_tstat_id,11);
    if(temp.Bias>0)
    {
        m_time_zone=_T("-");
        CString t;
        t.Format(_T("%d"),temp.Bias/60);
        m_time_zone=m_time_zone+t;
        if(i_temp==255)
        {
            m_building_time_zone.SetCurSel(12-temp.Bias/60);
            write_one(g_tstat_id,11,(short)(12-temp.Bias/60));
        }
        else if(i_temp>=0)
            m_building_time_zone.SetCurSel(i_temp);
    }
    else
    {
        m_time_zone=_T("+");
        CString t;
        t.Format(_T("%d"),temp.Bias/-60);
        m_time_zone=m_time_zone+t;
        if(i_temp==255)
        {
            m_building_time_zone.SetCurSel(12-temp.Bias/60);
            write_one(g_tstat_id,11,(short)(12-temp.Bias/60));
        }
        else if(i_temp>=0)
            m_building_time_zone.SetCurSel(i_temp);
    }

    UpdateData(FALSE);
    SETTIMER;
}
示例#2
0
void
__gnat_localtime_tzoff (const time_t *timer, const int *is_historic, long *off)
{
  TIME_ZONE_INFORMATION tzi;

  BOOL  rtx_active;
  DWORD tzi_status;

#ifdef RTX
  rtx_active = 1;
#else
  rtx_active = 0;
#endif

  (*Lock_Task) ();

  tzi_status = GetTimeZoneInformation (&tzi);

  /* Processing for RTX targets or cases where we simply want to extract the
     offset of the current time zone, regardless of the date. */

  if (rtx_active || !is_historic) {
    *off = tzi.Bias;

    /* The system is operating in the range covered by the StandardDate
       member. */
    if (tzi_status == TIME_ZONE_ID_STANDARD) {
       *off = *off + tzi.StandardBias;
    }

    /* The system is operating in the range covered by the DaylightDate
       member. */
    else if (tzi_status == TIME_ZONE_ID_DAYLIGHT) {
       *off = *off + tzi.DaylightBias;
    }

    *off = *off * -60;
  }

  /* Time zone offset calculations for a historic or future date */

  else {
    union
    {
      FILETIME ft_time;
      unsigned long long ull_time;
    } utc_time, local_time;

    SYSTEMTIME utc_sys_time, local_sys_time;
    BOOL status;

    /* First convert unix time_t structure to windows FILETIME format.  */
    utc_time.ull_time = ((unsigned long long) *timer + w32_epoch_offset)
                        * 10000000ULL;

    /* If GetTimeZoneInformation does not return a value between 0 and 2 then
       it means that we were not able to retrieve timezone informations. Note
       that we cannot use here FileTimeToLocalFileTime as Windows will use in
       always in this case the current timezone setting. As suggested on MSDN
       we use the following three system calls to get the right information.
       Note also that starting with Windows Vista new functions are provided
       to get timezone settings that depend on the year. We cannot use them as
       we still support Windows XP and Windows 2003.  */

    status = (tzi_status >= 0 && tzi_status <= 2)
      && FileTimeToSystemTime (&utc_time.ft_time, &utc_sys_time)
      && SystemTimeToTzSpecificLocalTime (&tzi, &utc_sys_time, &local_sys_time)
      && SystemTimeToFileTime (&local_sys_time, &local_time.ft_time);

    /* An error has occured, return invalid_tzoff */

    if (!status) {
      *off = __gnat_invalid_tzoff;
    }
    else {
      if (local_time.ull_time > utc_time.ull_time) {
        *off = (long) ((local_time.ull_time - utc_time.ull_time)
               / 10000000ULL);
      }
      else {
        *off = - (long) ((utc_time.ull_time - local_time.ull_time)
               / 10000000ULL);
      }
    }
  }

  (*Unlock_Task) ();
}
示例#3
0
文件: time.c 项目: AlexSteel/wine
/*********************************************************************
 *      GetDaylightFlag                                   (KERNEL32.@)
 *
 *  Specifies if daylight savings time is in operation.
 *
 * NOTES
 *  This function is called from the Win98's control applet timedate.cpl.
 *
 * RETURNS
 *  TRUE if daylight savings time is in operation.
 *  FALSE otherwise.
 */
BOOL WINAPI GetDaylightFlag(void)
{
    TIME_ZONE_INFORMATION tzinfo;
    return GetTimeZoneInformation( &tzinfo) == TIME_ZONE_ID_DAYLIGHT;
}
示例#4
0
// **************************************************************************
// GetValue ()
//
// Description:
//	Return a string representing the value of a variant.
//
// Parameters:
//  VARIANT		&vtVal		Input variant.
//	TCHAR		*pBuffer	Pointer to buffer for output string.
//	int			nBufLen		Size of output buffer.
//
// Returns:
//  void
// **************************************************************************
void CKItemPropertiesDlg::GetValue (VARIANT &vtVal,	// [in]	
									TCHAR *pBuffer, // [out]
									int nBufLen)	// [in]
	{
	ASSERT (pBuffer != NULL);
	ASSERT (nBufLen > 0);

	// Declare a CString to help construct result string:
	CString strVal;

	// Format string according to data type:
	switch (vtVal.vt)
		{
		case VT_BOOL:
			strVal.Format (_T("%d"), vtVal.boolVal);
			break;

		case VT_UI1:
			strVal.Format (_T("%u"), vtVal.bVal);
			break;

		case VT_I1:
			strVal.Format (_T("%d"), vtVal.cVal);
			break;

		case VT_UI2:
			strVal.Format (_T("%u"), vtVal.uiVal);
			break;

		case VT_I2:
			strVal.Format (_T("%d"), vtVal.iVal);
			break;

		case VT_UI4:
			strVal.Format (_T("%u"), vtVal.ulVal);
			break;

		case VT_I4:
			strVal.Format (_T("%d"), vtVal.lVal);
			break;

		case VT_R4:
			strVal.Format (_T("%G"), vtVal.fltVal);
			break;

		case VT_R8:
			strVal.Format (_T("%G"), vtVal.dblVal);
			break;

		case VT_BSTR:
			strVal = vtVal.bstrVal;
			break;

		case VT_DATE:
			{
			bool bSuccess = false;

			// Cariant time to system time (UTC):
			SYSTEMTIME systime;
			if (VariantTimeToSystemTime (vtVal.dblVal, &systime))
				{
				// Get time zone information:
				TIME_ZONE_INFORMATION tTZI;
				if (GetTimeZoneInformation (&tTZI) != TIME_ZONE_ID_INVALID)
					{
					// Localize system time:
					SYSTEMTIME systimelocal;
					if (SystemTimeToTzSpecificLocalTime (&tTZI, &systime, &systimelocal))
						{
						strVal.Format (_T("%02d:%02d:%02d"), 
							systimelocal.wHour, systimelocal.wMinute, systimelocal.wSecond);			

						bSuccess = true;
						}
					}
				}
			
			if (!bSuccess)
				strVal = _T("???");
			}
			break;

		case VT_UI1	| VT_ARRAY:
		case VT_I1	| VT_ARRAY:
		case VT_UI2	| VT_ARRAY:
		case VT_I2	| VT_ARRAY:
		case VT_UI4	| VT_ARRAY:
		case VT_I4	| VT_ARRAY:
		case VT_R4	| VT_ARRAY:
		case VT_R8	| VT_ARRAY:
			{
			CSafeArray *pSafeArr = (CSafeArray *) vtVal.parray;
			DWORD dwCols = pSafeArr->GetNumCols ();
			DWORD dwSize = pSafeArr->GetByteLength ();
			ULONG cbElements = pSafeArr->cbElements;
			LPBYTE lpByte = (LPBYTE)pSafeArr->pvData;
			DWORD dwCol = 0;

			// Start row delimiter:
			strVal = _T("[ ");

			// Cycle through the elements:
			for (DWORD i = 0; i < dwSize; i += cbElements, lpByte += cbElements)
				{
				TCHAR szNum[32];

				// Format element according to data size:
				if (cbElements == 1)
					{
					if (vtVal.vt ==	(VT_UI1 | VT_ARRAY))
						_stprintf (szNum, _T("%u"), *lpByte);
					else
						_stprintf (szNum, _T("%d"), *(char *)lpByte);
					}
				
				else if (cbElements == 2)
					{
					if (vtVal.vt ==	(VT_UI2 | VT_ARRAY))
						_stprintf (szNum, _T("%u"), *(WORD *)lpByte);
					else 
						_stprintf (szNum, _T("%d"), *(short *)lpByte);
					}
				
				else if (cbElements == 4)
					{
					if (vtVal.vt ==	(VT_R4	| VT_ARRAY))
						_stprintf (szNum, _T("%G"), *(float *)lpByte);
					else if (vtVal.vt ==	(VT_UI4	| VT_ARRAY))
						_stprintf (szNum, _T("%u"), *(DWORD *)lpByte);
					else if (vtVal.vt ==	(VT_I4	| VT_ARRAY))
						_stprintf (szNum, _T("%d"), *(DWORD *)lpByte);
					}

				else if (cbElements == 8)
					_stprintf (szNum, _T("%G"), *(double *)lpByte);

				else
					{
					ASSERT (FALSE);
					}

				// Delimit each element within the row with a comma:
				if (dwCol != 0)
					strVal += _T(", ");

				// Append the formatted element data:
				strVal += szNum;

				// Terminate each row (except the last):
				if (++dwCol == dwCols)
					{
					if (i < dwSize - cbElements) 
						strVal += _T(" ] [ ");

					dwCol = 0;
					}
				}

			// End delimiter:
			strVal += _T(" ]");
			}
			break;

		default:
			// Unsupported datatype:
			strVal = _T ("<Bad VARTYPE>");
			break;
		}

	// Copy value to output buffer:
	lstrcpyn (pBuffer, strVal, nBufLen);
	}
示例#5
0
/*
** Read the options specified in the ini file.
**
*/
void CMeasureTime::ReadOptions(CConfigParser& parser, const WCHAR* section)
{
	CMeasure::ReadOptions(parser, section);

	m_Format = parser.ReadString(section, L"Format", L"");

	m_TimeStamp = parser.ReadFloat(section, L"TimeStamp", -1);

	if (m_TimeStamp < 0.0)
	{
		const WCHAR* timezone = parser.ReadString(section, L"TimeZone", L"local").c_str();
		if (_wcsicmp(L"local", timezone) == 0)
		{
			SYSTEMTIME sysLocalTime, sysUTCTime;
			GetLocalTime(&sysLocalTime);
			GetSystemTime(&sysUTCTime);

			FILETIME ftLocalTime, ftUTCTime;
			SystemTimeToFileTime(&sysLocalTime, &ftLocalTime);
			SystemTimeToFileTime(&sysUTCTime, &ftUTCTime);

			LARGE_INTEGER largeInt1, largeInt2;
			largeInt1.HighPart = ftLocalTime.dwHighDateTime;
			largeInt1.LowPart = ftLocalTime.dwLowDateTime;
			largeInt2.HighPart = ftUTCTime.dwHighDateTime;
			largeInt2.LowPart = ftUTCTime.dwLowDateTime;

			m_DeltaTime.QuadPart = largeInt1.QuadPart - largeInt2.QuadPart;
		}
		else
		{
			double zone = parser.ParseDouble(timezone, 0.0);
			bool dst = 1 == parser.ReadInt(section, L"DaylightSavingTime", 1);

			struct tm* today;
			time_t now;
			time(&now);
			today = localtime(&now);

			if (dst && today->tm_isdst)
			{
				// Add DST
				TIME_ZONE_INFORMATION tzi;
				GetTimeZoneInformation(&tzi);

				m_DeltaTime.QuadPart = (LONGLONG)((zone * 3600) - tzi.DaylightBias * 60) * 10000000;
			}
			else
			{
				m_DeltaTime.QuadPart = (LONGLONG)(zone * 3600) * 10000000;
			}
		}
	}
	else
	{
		m_DeltaTime.QuadPart = 0;
	}

	if (!m_Initialized)
	{
		// Initialize m_Time to avoid causing EINVAL in TimeToString() until calling UpdateValue()
		FillCurrentTime();
	}
}
示例#6
0
文件: time.c 项目: ohmann/checkapi
APR_DECLARE(apr_status_t) apr_time_exp_lt(apr_time_exp_t *result,
                                          apr_time_t input)
{
    SYSTEMTIME st;
    FILETIME ft, localft;

    AprTimeToFileTime(&ft, input);

#if APR_HAS_UNICODE_FS && !defined(_WIN32_WCE)
    IF_WIN_OS_IS_UNICODE
    {
        TIME_ZONE_INFORMATION *tz;
        SYSTEMTIME localst;
        apr_time_t localtime;

        get_local_timezone(&tz);

        FileTimeToSystemTime(&ft, &st);

        /* The Platform SDK documents that SYSTEMTIME/FILETIME are
         * generally UTC.  We use SystemTimeToTzSpecificLocalTime
         * because FileTimeToLocalFileFime is documented that the
         * resulting time local file time would have DST relative
         * to the *present* date, not the date converted.
         */
        SystemTimeToTzSpecificLocalTime(tz, &st, &localst);
        SystemTimeToAprExpTime(result, &localst);
        result->tm_usec = (apr_int32_t) (input % APR_USEC_PER_SEC);


        /* Recover the resulting time as an apr time and use the
         * delta for gmtoff in seconds (and ignore msec rounding)
         */
        SystemTimeToFileTime(&localst, &localft);
        FileTimeToAprTime(&localtime, &localft);
        result->tm_gmtoff = (int)apr_time_sec(localtime)
                          - (int)apr_time_sec(input);

        /* To compute the dst flag, we compare the expected
         * local (standard) timezone bias to the delta.
         * [Note, in war time or double daylight time the
         * resulting tm_isdst is, desireably, 2 hours]
         */
        result->tm_isdst = (result->tm_gmtoff / 3600)
                         - (-(tz->Bias + tz->StandardBias) / 60);
    }
#endif
#if APR_HAS_ANSI_FS || defined(_WIN32_WCE)
    ELSE_WIN_OS_IS_ANSI
    {
        TIME_ZONE_INFORMATION tz;
	/* XXX: This code is simply *wrong*.  The time converted will always
         * map to the *now current* status of daylight savings time.
         */

        FileTimeToLocalFileTime(&ft, &localft);
        FileTimeToSystemTime(&localft, &st);
        SystemTimeToAprExpTime(result, &st);
        result->tm_usec = (apr_int32_t) (input % APR_USEC_PER_SEC);

        switch (GetTimeZoneInformation(&tz)) {
            case TIME_ZONE_ID_UNKNOWN:
                result->tm_isdst = 0;
                /* Bias = UTC - local time in minutes
                 * tm_gmtoff is seconds east of UTC
                 */
                result->tm_gmtoff = tz.Bias * -60;
                break;
            case TIME_ZONE_ID_STANDARD:
                result->tm_isdst = 0;
                result->tm_gmtoff = (tz.Bias + tz.StandardBias) * -60;
                break;
            case TIME_ZONE_ID_DAYLIGHT:
                result->tm_isdst = 1;
                result->tm_gmtoff = (tz.Bias + tz.DaylightBias) * -60;
                break;
            default:
                /* noop */;
        }
    }
#endif

    return APR_SUCCESS;
}
示例#7
0
文件: time.c 项目: Barrell/wine
static void test_mktime(void)
{
    TIME_ZONE_INFORMATION tzinfo;
    DWORD res =  GetTimeZoneInformation(&tzinfo);
    struct tm my_tm, sav_tm;
    time_t nulltime, local_time;
    char TZ_env[256];
    char buffer[64];
    int year;
    time_t ref, secs;

    year = get_test_year( &ref );
    ref += SECSPERDAY;

    ok (res != TIME_ZONE_ID_INVALID, "GetTimeZoneInformation failed\n");
    WideCharToMultiByte( CP_ACP, 0, tzinfo.StandardName, -1, buffer, sizeof(buffer), NULL, NULL );
    trace( "bias %d std %d dst %d zone %s\n",
           tzinfo.Bias, tzinfo.StandardBias, tzinfo.DaylightBias, buffer );
    /* Bias may be positive or negative, to use offset of one day */
    my_tm = *localtime(&ref);  /* retrieve current dst flag */
    secs = SECSPERDAY - tzinfo.Bias * SECSPERMIN;
    secs -= (my_tm.tm_isdst ? tzinfo.DaylightBias : tzinfo.StandardBias) * SECSPERMIN;
    my_tm.tm_mday = 1 + secs/SECSPERDAY;
    secs = secs % SECSPERDAY;
    my_tm.tm_hour = secs / SECSPERHOUR;
    secs = secs % SECSPERHOUR;
    my_tm.tm_min = secs / SECSPERMIN;
    secs = secs % SECSPERMIN;
    my_tm.tm_sec = secs;

    my_tm.tm_year = year;
    my_tm.tm_mon  =  0;

    sav_tm = my_tm;

    local_time = mktime(&my_tm);
    ok(local_time == ref, "mktime returned %u, expected %u\n",
       (DWORD)local_time, (DWORD)ref);
    /* now test some unnormalized struct tm's */
    my_tm = sav_tm;
    my_tm.tm_sec += 60;
    my_tm.tm_min -= 1;
    local_time = mktime(&my_tm);
    ok(local_time == ref, "Unnormalized mktime returned %u, expected %u\n",
        (DWORD)local_time, (DWORD)ref);
    ok( my_tm.tm_year == sav_tm.tm_year && my_tm.tm_mon == sav_tm.tm_mon &&
        my_tm.tm_mday == sav_tm.tm_mday && my_tm.tm_hour == sav_tm.tm_hour &&
        my_tm.tm_sec == sav_tm.tm_sec,
            "mktime returned %2d-%02d-%02d %02d:%02d expected %2d-%02d-%02d %02d:%02d\n",
            my_tm.tm_year,my_tm.tm_mon,my_tm.tm_mday,
            my_tm.tm_hour,my_tm.tm_sec,
            sav_tm.tm_year,sav_tm.tm_mon,sav_tm.tm_mday,
            sav_tm.tm_hour,sav_tm.tm_sec);
    my_tm = sav_tm;
    my_tm.tm_min -= 60;
    my_tm.tm_hour += 1;
    local_time = mktime(&my_tm);
    ok(local_time == ref, "Unnormalized mktime returned %u, expected %u\n",
       (DWORD)local_time, (DWORD)ref);
    ok( my_tm.tm_year == sav_tm.tm_year && my_tm.tm_mon == sav_tm.tm_mon &&
        my_tm.tm_mday == sav_tm.tm_mday && my_tm.tm_hour == sav_tm.tm_hour &&
        my_tm.tm_sec == sav_tm.tm_sec,
            "mktime returned %2d-%02d-%02d %02d:%02d expected %2d-%02d-%02d %02d:%02d\n",
            my_tm.tm_year,my_tm.tm_mon,my_tm.tm_mday,
            my_tm.tm_hour,my_tm.tm_sec,
            sav_tm.tm_year,sav_tm.tm_mon,sav_tm.tm_mday,
            sav_tm.tm_hour,sav_tm.tm_sec);
    my_tm = sav_tm;
    my_tm.tm_mon -= 12;
    my_tm.tm_year += 1;
    local_time = mktime(&my_tm);
    ok(local_time == ref, "Unnormalized mktime returned %u, expected %u\n",
       (DWORD)local_time, (DWORD)ref);
    ok( my_tm.tm_year == sav_tm.tm_year && my_tm.tm_mon == sav_tm.tm_mon &&
        my_tm.tm_mday == sav_tm.tm_mday && my_tm.tm_hour == sav_tm.tm_hour &&
        my_tm.tm_sec == sav_tm.tm_sec,
            "mktime returned %2d-%02d-%02d %02d:%02d expected %2d-%02d-%02d %02d:%02d\n",
            my_tm.tm_year,my_tm.tm_mon,my_tm.tm_mday,
            my_tm.tm_hour,my_tm.tm_sec,
            sav_tm.tm_year,sav_tm.tm_mon,sav_tm.tm_mday,
            sav_tm.tm_hour,sav_tm.tm_sec);
    my_tm = sav_tm;
    my_tm.tm_mon += 12;
    my_tm.tm_year -= 1;
    local_time = mktime(&my_tm);
    ok(local_time == ref, "Unnormalized mktime returned %u, expected %u\n",
       (DWORD)local_time, (DWORD)ref);
    ok( my_tm.tm_year == sav_tm.tm_year && my_tm.tm_mon == sav_tm.tm_mon &&
        my_tm.tm_mday == sav_tm.tm_mday && my_tm.tm_hour == sav_tm.tm_hour &&
        my_tm.tm_sec == sav_tm.tm_sec,
            "mktime returned %2d-%02d-%02d %02d:%02d expected %2d-%02d-%02d %02d:%02d\n",
            my_tm.tm_year,my_tm.tm_mon,my_tm.tm_mday,
            my_tm.tm_hour,my_tm.tm_sec,
            sav_tm.tm_year,sav_tm.tm_mon,sav_tm.tm_mday,
            sav_tm.tm_hour,sav_tm.tm_sec);
    /* now a bad time example */
    my_tm = sav_tm;
    my_tm.tm_year = 69;
    local_time = mktime(&my_tm);
    ok((local_time == -1), "(bad time) mktime returned %d, expected -1\n", (int)local_time);

    my_tm = sav_tm;
    /* TEST that we are independent from the TZ variable */
    /*Argh, msvcrt doesn't have setenv() */
    _snprintf(TZ_env,255,"TZ=%s",(getenv("TZ")?getenv("TZ"):""));
    putenv("TZ=GMT");
    nulltime = mktime(&my_tm);
    ok(nulltime == ref,"mktime returned 0x%08x\n",(DWORD)nulltime);
    putenv(TZ_env);
}
示例#8
0
int CSmtpClient::SendEmailToRecipient(CString sSmtpServer, CEmailMessage* msg)
{
	// This method connects to the given SMTP server and tries to send
	// the E-mail message.

    int status = 1; // Resulting status.
    strconv_t strconv; // String convertor
    struct addrinfo *result = NULL; 
    struct addrinfo *ptr = NULL;
    struct addrinfo hints;
	std::string sEncodedLogin;
	std::string sEncodedPassword;	
	CString sBodyTo; //Vojtech: Lines of the "To:" and "Cc:" lines, that will become part of the e-mail header.
    int iResult = -1;  
    CString sPostServer;
	CString sServiceName;	
	SOCKET sock = INVALID_SOCKET;
    CString sMsg, str;
    std::set<CString>::iterator it;
    CString sStatusMsg;
	const int RESPONSE_BUFF_SIZE = 4096;
	char response[RESPONSE_BUFF_SIZE];	
	int res = SOCKET_ERROR;    
    std::string sEncodedFileData;
	bool bESMTP = false;

	// Convert port number to string
    sServiceName.Format(_T("%d"), 
        m_sServer.IsEmpty()?25:m_nPort);  
    
    // Prepare message text (we need to replace "\n" by "\r\n" and remove . from message). 
	CString sMessageText = msg->GetText();
    sMessageText.Replace(_T("\n"),_T("\r\n"));
    sMessageText.Replace(_T("\r\n.\r\n"), _T("\r\n*\r\n"));
    LPCWSTR lpwszMessageText = strconv.t2w(sMessageText.GetBuffer(0));
	// Convert the text to UTF-8 encoding
    std::string sUTF8Text = UTF16toUTF8(lpwszMessageText);
	
	// Check that all attachments exist
	int i;
	for(i=0; i<msg->GetAttachmentCount(); i++)
    {
		CString sFileName = msg->GetAttachment(i);
        if(CheckAttachmentOK(sFileName)!=0)
        {
			// Some attachment file does not present
            sStatusMsg.Format(_T("Attachment not found: %s"), sFileName);
            m_scn->SetProgress(sStatusMsg, 1);
            return 2; // critical error
        }
    }

	// Add a message to log
    sStatusMsg.Format(_T("Getting address info of %s port %s"), sSmtpServer, CString(sServiceName));
    m_scn->SetProgress(sStatusMsg, 1);
	
	// Prepare to open socket
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;  

    LPCSTR lpszSmtpServer = strconv.t2a(sSmtpServer);
    LPCSTR lpszServiceName = strconv.t2a(sServiceName);
    iResult = getaddrinfo(lpszSmtpServer, lpszServiceName, &hints, &result);
    if(iResult!=0)
        goto exit;

	// For each interface do
    for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) 
    {
		// Check if cancelled
        if(m_scn->IsCancelled()) {status = 2; goto exit;}

		// Add a message to log
        sStatusMsg.Format(_T("Creating socket"));
        m_scn->SetProgress(sStatusMsg, 1);

		// Open socket
        sock = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
        if(sock==INVALID_SOCKET)
        {
            m_scn->SetProgress(_T("Socket creation failed."), 1);
            goto exit;
        }

		// Add a message to log
        sStatusMsg.Format(_T("Connecting to SMTP server %s port %s"), sSmtpServer, CString(sServiceName));
        m_scn->SetProgress(sStatusMsg, 1);

		// Connect socket
        res = connect(sock, ptr->ai_addr, (int)ptr->ai_addrlen);
        if(res!=SOCKET_ERROR)
            break; // If successfull, break the loop    

		// Close socket
        closesocket(sock);
    }

	// Check if socket open
    if(res==SOCKET_ERROR)
	{
		sStatusMsg.Format(_T("Socket connection error."));
		m_scn->SetProgress(sStatusMsg, 5);
        goto exit;
	}

	// Add a message to log
    sStatusMsg.Format(_T("Connected OK."));
    m_scn->SetProgress(sStatusMsg, 5);

	// Check cancel status
    if(m_scn->IsCancelled()) {status = 2; goto exit;}

	m_scn->SetProgress(_T("Waiting for greeting message from SMTP server..."), 1);
	
	// Wait until server send us greeting message, for example:
	// 220 mail.company.tld ESMTP CommuniGate Pro 5.1.4i is glad to see you!    
	res=SendMsg(sock, NULL, response, RESPONSE_BUFF_SIZE);
    if(res==SOCKET_ERROR)
    {
		// Error - server did not send us greeting message
        sStatusMsg.Format(_T("Failed to receive greeting message from SMTP server (recv code %d)."), res);
        m_scn->SetProgress(sStatusMsg, 1);
        goto exit;
    }
	
	// Check the code server returned (expect code 220).
    if(220!=GetMessageCode(response)) 
    {
		// Invalid greeting
		m_scn->SetProgress(_T("Invalid greeting message."), 1);
        goto exit;
    }
	    
	// Add a message to log
    sStatusMsg.Format(_T("Sending EHLO"));
    m_scn->SetProgress(sStatusMsg, 1);
	    
    res=SendMsg(sock, _T("EHLO CrashSender\r\n"), response, RESPONSE_BUFF_SIZE);
	// Check return code (expect code 250)
    if(res==250)
    {
		sStatusMsg = CString(_T("EHLO command not supported"));
		bESMTP = true;
	}
	
	if(!bESMTP)
	{
		// Server may not understand EHLO, try HELO
		sStatusMsg.Format(_T("Sending HELO"));
		m_scn->SetProgress(sStatusMsg, 1);

		res=SendMsg(sock, _T("HELO CrashSender\r\n"), response, RESPONSE_BUFF_SIZE);
		// Expect code 250
		if(res!=250)
		{
			// Add a message to log
			sStatusMsg = CString(_T("HELO command not supported"));
			m_scn->SetProgress(sStatusMsg, 0);   
			goto exit;
		}
    }	
		
	// Check whether to perform authorization procedure
	if(!m_sLogin.IsEmpty())
	{
		if(!bESMTP)
		{
			sStatusMsg.Format(_T("SMTP server does not support authorization."));
			m_scn->SetProgress(sStatusMsg, 1);
		}

		sStatusMsg.Format(_T("Sending AUTH LOGIN."));
		m_scn->SetProgress(sStatusMsg, 1);

		// SMTP authorization
		// AUTH <SP> LOGIN <CRLF>		
		res=SendMsg(sock, _T("AUTH LOGIN\r\n"), response, RESPONSE_BUFF_SIZE);		
				
    	if(res!=334)
		{
			m_scn->SetProgress(_T("Unexpected server response"), 0);
			goto exit;
		}

		// Send login
		sStatusMsg.Format(_T("Sending login"));
		m_scn->SetProgress(sStatusMsg, 1);
		// Convert login to ASCII
		LPCSTR lpszLogin = strconv.t2a(m_sLogin);
		// And encode it in BASE-64
		sEncodedLogin = base64_encode(reinterpret_cast<const unsigned char*>(lpszLogin),(int)strlen(lpszLogin));
		sEncodedLogin+="\r\n";
		LPCTSTR lpwszLogin = strconv.a2t((LPCSTR)(sEncodedLogin.c_str()));
		memset(response,0,1024);   
		// Send it
		res=SendMsg(sock, lpwszLogin, response, 1024);
		// Check return code - expect 334
		if (res!=334)
		{
			sStatusMsg = _T("Login not accepted");
			m_scn->SetProgress(sStatusMsg, 0);    
			goto exit;
		}
    
		// Send password
		sStatusMsg.Format(_T("Sending password"));
		m_scn->SetProgress(sStatusMsg, 1);
		// Convert to ASCII
		LPCSTR lpszPassword = strconv.t2a(m_sPassword);
		// BASE-64 encode
		sEncodedPassword = base64_encode(reinterpret_cast<const unsigned char*>(lpszPassword),(int)strlen(lpszPassword));
		sEncodedPassword+="\r\n";
		LPCTSTR lpwszPassword = strconv.a2t((LPCSTR)(sEncodedPassword.c_str()));
		memset(response,0,1024);
		// Send it
		res=SendMsg(sock, lpwszPassword, response, 1024);
		if(res!=235)
		{
			sStatusMsg = _T("Authorization failed");
			m_scn->SetProgress(sStatusMsg, 0); 
		}
    }
  
	// Next send sender and recipient info
    sStatusMsg.Format(_T("Sending sender and recipient information"));
    m_scn->SetProgress(sStatusMsg, 1);

	// Send MAIL FROM
	sMsg.Format(_T("MAIL FROM:<%s>\r\n"), msg->GetSenderAddress());	
    res=SendMsg(sock, sMsg, response, RESPONSE_BUFF_SIZE);
	if (res!=250)
	{
        sStatusMsg = _T("Unexpected status code");
        m_scn->SetProgress(sStatusMsg, 0);    
        goto exit;
    }

	// Process multiple e-mail recipients.		
	for(i=0; i<msg->GetRecipientCount(); i++)
	{
		sMsg.Format(i==0 ? _T("To: <%s>\r\n") : _T("Cc: <%s>\r\n"), msg->GetRecipientAddress(i));
		sBodyTo += sMsg;
		sMsg.Format(_T("RCPT TO:<%s>\r\n"), msg->GetRecipientAddress(i));
		res=SendMsg(sock, sMsg, response, RESPONSE_BUFF_SIZE);
		if(res!=250)
		{
			sStatusMsg = _T("Unexpected status code");
			m_scn->SetProgress(sStatusMsg, 0);
			goto exit;
		}
	}
		
    sStatusMsg.Format(_T("Start sending email data"));
    m_scn->SetProgress(sStatusMsg, 1);

    // Send DATA	
    res=SendMsg(sock, _T("DATA\r\n"), response, RESPONSE_BUFF_SIZE);
	if (res!=354)
	{
        sStatusMsg = _T("Unexpected status code");
        m_scn->SetProgress(sStatusMsg, 0);    
        goto exit;
    }

    // Get current time
    time_t cur_time;
    time(&cur_time);
    char szDateTime[64] = "";
    
#if _MSC_VER >= 1400
	struct tm ltimeinfo;
    localtime_s(&ltimeinfo, &cur_time );
	strftime(szDateTime, 64,  "%a, %d %b %Y %H:%M:%S", &ltimeinfo);
#else
	struct tm* ltimeinfo = localtime(&cur_time );
	strftime(szDateTime, 64,  "%a, %d %b %Y %H:%M:%S", ltimeinfo);
#endif
        
    TIME_ZONE_INFORMATION tzi;
    GetTimeZoneInformation(&tzi);

    int diff_hours = -tzi.Bias/60;
    int diff_mins = abs(tzi.Bias%60);
	// Send date header
    str.Format(_T("Date: %s %c%02d%02d\r\n"), strconv.a2t(szDateTime), diff_hours>=0?'+':'-', diff_hours, diff_mins);
    sMsg = str;
	// Send From header
	str.Format(_T("From: <%s>\r\n"), msg->GetSenderAddress());
    sMsg  += str;
    sMsg += sBodyTo;
	// Send subject
	str.Format(_T("Subject: %s\r\n"), msg->GetSubject());
    sMsg += str;
	// Send MIME-Version header
    sMsg += "MIME-Version: 1.0\r\n";
	// Send Content-Type
    sMsg += "Content-Type: multipart/mixed; boundary=KkK170891tpbkKk__FV_KKKkkkjjwq\r\n";
    sMsg += "\r\n\r\n";
    res = SendMsg(sock, sMsg);
    if(res!=sMsg.GetLength())
        goto exit;

    /* Message text */

    sStatusMsg.Format(_T("Sending message text"));
    m_scn->SetProgress(sStatusMsg, 15);

    sMsg =  "--KkK170891tpbkKk__FV_KKKkkkjjwq\r\n";
    sMsg += "Content-Type: text/plain; charset=UTF-8\r\n";
    sMsg += "\r\n";  
    sMsg += sUTF8Text.c_str();
    sMsg += "\r\n";
    res = SendMsg(sock, sMsg);
    if(res!=sMsg.GetLength())
        goto exit;

    sStatusMsg.Format(_T("Sending attachments"));
    m_scn->SetProgress(sStatusMsg, 1);

    /* Attachments. */
	for(i=0; i<msg->GetAttachmentCount(); i++)
    {    
		CString sFileName = msg->GetAttachment(i);
        sFileName.Replace('/', '\\');
        CString sDisplayName = sFileName.Mid(sFileName.ReverseFind('\\')+1);

        // Header
        sMsg =  "\r\n--KkK170891tpbkKk__FV_KKKkkkjjwq\r\n";
        sMsg += "Content-Type: application/octet-stream\r\n";
        sMsg += "Content-Transfer-Encoding: base64\r\n";
        sMsg += "Content-Disposition: attachment; filename=\"";
        sMsg += sDisplayName;
        sMsg += "\"\r\n";
        sMsg += "\r\n";
        res = SendMsg(sock, sMsg);
        if(res!=sMsg.GetLength())
            goto exit;

        // Encode data
        LPBYTE buf = NULL;
        //int buf_len = 0;
        int nEncode=Base64EncodeAttachment(sFileName, sEncodedFileData);
        if(nEncode!=0)
        {
            sStatusMsg.Format(_T("Error BASE64-encoding attachment %s"), sFileName);
            m_scn->SetProgress(sStatusMsg, 1);
            goto exit;
        }

        // Send encoded data
        sMsg = sEncodedFileData.c_str();        
        res = SendMsg(sock, sMsg);
        if(res!=sMsg.GetLength())
            goto exit;

        delete [] buf;
    }

    sMsg =  "\r\n--KkK170891tpbkKk__FV_KKKkkkjjwq--";
    res = SendMsg(sock, sMsg);
    if(res!=sMsg.GetLength())
        goto exit;

    // End of message marker	
    res = SendMsg(sock, _T("\r\n.\r\n"), response, RESPONSE_BUFF_SIZE);
	if (res!=250)
	{
        goto exit;
    }

    // Quit	
    res = SendMsg(sock, _T("QUIT\r\n"), response, RESPONSE_BUFF_SIZE);
	// Expect code 221
	if(res!=221)
	{
        goto exit;
    }

    // OK.
    status = 0;

exit:

    if(m_scn->IsCancelled()) 
        status = 2;

    sStatusMsg.Format(_T("Finished with error code %d"), status);
    m_scn->SetProgress(sStatusMsg, 100, false);

    // Clean up
    closesocket(sock);
    freeaddrinfo(result);  
    return status;
}
示例#9
0
文件: test1.c 项目: Afshintm/coreclr
int __cdecl main(int argc, char **argv)
{  
    time_t LTime;
    char  *DateResult;      
    TIME_ZONE_INFORMATION tzInformation;

    /*
     * Initialize the PAL and return FAILURE if this fails
     */

    if (PAL_Initialize(argc, argv))
    {
       return FAIL;
    }

    // Get the current timezone information
    GetTimeZoneInformation(&tzInformation);

    /*
     * Test #1
     */
    
    /* set the valid date in time_t format, adjusted for current time zone*/
    LTime = VAL_SUN_JAN_17_2038 + (tzInformation.Bias * 60);

    /* convert it to string using ctime*/
    DateResult = ctime( &LTime );

    /* if it's null, ctime failed*/
    if (DateResult == NULL)
    {
        Fail ("ERROR: (Test #1) ctime returned NULL. Expected string\n");
    }
    
    /* test if the entire string can ba access normaly    */
    if(IsBadReadPtr(DateResult, STR_TIME_SIZE)==0)
    {
        /* compare result with win2000 result */
        if(strcmp( DateResult, STR_SUN_JAN_17_2038)!=0)
        {
            Fail("ERROR: (Test #1) ctime returned an unexpected string " 
                 "%s, expexted string is %s\n"
                 ,DateResult, STR_SUN_JAN_17_2038);
        }
    }
    else
    {
        Fail ("ERROR: (Test #1) ctime returned a bad pointer.\n");
    }


    /*
     * Test #2
     */

    /* Set the valid date in time_t format, adjusted for current time zone */
    LTime = VAL_FRI_JAN_02_1970 + (tzInformation.Bias * 60);

    /* convert it to string using ctime   */
    DateResult = ctime( &LTime );

    /* if it's null, ctime failed*/
    if (DateResult == NULL)
    {
        Fail ("ERROR: (Test #2) ctime returned NULL. Expected string\n");
    }   

    /* test if the entire string can ba access normaly    */
    if(IsBadReadPtr(DateResult, STR_TIME_SIZE)==0)
    {
        /* compare result with win2000 result  */
        if (strcmp(DateResult, STR_FRI_JAN_02_1970) != 0
            && strcmp(DateResult, STR_FRI_JAN__2_1970) != 0)
        {
            Fail("ERROR: (Test #2) ctime returned an unexpected string " 
                 "%s, expected string is %s\n"
                 ,DateResult, STR_FRI_JAN_02_1970);
        }
    }
    else
    {
        Fail ("ERROR: (Test #2) ctime returned a bad pointer.\n");
    }       


    
    /*
     * Test #3
     */

    /* specify an invalid time  */
    LTime = -1;

    /* try to convert it        */
    DateResult = ctime( &LTime );    

    /* Check the result for errors, should fail in this case */
    if (DateResult != NULL)
    {
        Fail ("ERROR: (Test #3) ctime returned something different from NULL.:"
              "Expected NULL\n");
    }


    PAL_Terminate();
    return PASS;
}
示例#10
0
int Timezone::dst()
{
	TIME_ZONE_INFORMATION tzInfo;
	DWORD dstFlag = GetTimeZoneInformation(&tzInfo);
	return dstFlag == TIME_ZONE_ID_DAYLIGHT ? -tzInfo.DaylightBias*60 : 0;
}
示例#11
0
int __cdecl main(int argc, char **argv)
{

    FILETIME UTCTime, LocalTime;
    ULONG64 FullFileTime, FullLocalTime, CorrectTime;
    TIME_ZONE_INFORMATION ZoneInfo;
    int DeltaBetweenLocalAndUTC;
    int result;

    if (0 != PAL_Initialize(argc,argv))
    {
        return FAIL;
    }

    /* This is a valid UTC file time generated with GetFileTime */
    UTCTime.dwLowDateTime = 1867954880;
    UTCTime.dwHighDateTime = 29437095;
  
    /* Call the function */
    result = FileTimeToLocalFileTime(&UTCTime,&LocalTime);
  
    if(result == 0) 
    {
        Fail("ERROR: FileTimeToLocalTime has returned zero, which "
               "indicates that it failed.");
    }

    /* We need to get the time zone that the user is running in. */
    result = GetTimeZoneInformation(&ZoneInfo);

    /* Use the Time Zone Information to construct the delta between UTC
       and local time -- in hours.
    */
    
    if(result == TIME_ZONE_ID_STANDARD)
    {
        DeltaBetweenLocalAndUTC = 
            (ZoneInfo.Bias + ZoneInfo.StandardBias);  
    }
    else if (result == TIME_ZONE_ID_DAYLIGHT) 
    {
        DeltaBetweenLocalAndUTC = 
            (ZoneInfo.Bias + ZoneInfo.DaylightBias); 
    }
    else 
    {
        DeltaBetweenLocalAndUTC = (ZoneInfo.Bias);
    }
 
    /* Change the UTC and Local FILETIME structures into ULONG64 
       types 
    */
  
    FullFileTime = ((((ULONG64)UTCTime.dwHighDateTime)<<32) | 
                    ((ULONG64)UTCTime.dwLowDateTime));
  
    FullLocalTime = ((((ULONG64)LocalTime.dwHighDateTime)<<32) | 
                     ((ULONG64)LocalTime.dwLowDateTime));

    /* This magic number is 10000000 * 60 * 60 -- which is the
       number of 100s of Nanseconds in a second, multiplied by the number
       of seconds in a minute, multiplied by the number of minutes in an
       hour.
     
       The correct time is the delta in hundreds of nanoseconds between
       Local and UTC times.
    */
  
    CorrectTime = 600000000 * ((ULONG64)DeltaBetweenLocalAndUTC);
  
    /* Now check to ensure that the difference between the Local and UTC
       times that was calculated with the function equals what it should be.
    */
    if((FullFileTime - FullLocalTime) != CorrectTime)
    {
        Fail("ERROR: The LocalFileTime that was returned is not equal to "
               "what the LocalFileTime should have been.");
    } 
  
    PAL_Terminate();
    return PASS;
}
示例#12
0
int Timezone::utcOffset()
{
	TIME_ZONE_INFORMATION tzInfo;
	DWORD dstFlag = GetTimeZoneInformation(&tzInfo);
	return -tzInfo.Bias*60;
}
示例#13
0
BOOL CALLBACK CDateTime::DateTimeProc(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam) 
{
	static HWND hwndTimeZone;
	static HKEY g_hKey = NULL;
	static CDlgAnchor g_dlgAnchor;

    switch (message) 
    { 
		case WM_SIZE :
		{
			g_dlgAnchor.OnSize();
		}
		break;
        case WM_INITDIALOG:
        {
			g_dlgAnchor.Init(hwndDlg);
			g_dlgAnchor.Add(IDC_COMBO_TIMEZONE, ANCHOR_ALL &~ ANCHOR_BOTTOM);

			hwndTimeZone = GetDlgItem(hwndDlg, IDC_COMBO_TIMEZONE);

			TIME_ZONE_INFORMATION info = {0};
			GetTimeZoneInformation(&info);

			int index = ComboBox_AddString(hwndTimeZone, info.StandardName);
			index = ComboBox_SetItemData(hwndTimeZone, index, info.StandardBias);

			g_hKey = (HKEY)lParam;
			DWORD dwOffset = 0;
			RegistryGetDWORD(g_hKey, NULL, REG_TimeOffset, &dwOffset); 

			ComboBox_SetCurSel(hwndTimeZone, 0);

            SHINITDLGINFO shidi;
            // Create a Done button and size it.
            shidi.dwMask = SHIDIM_FLAGS;
            shidi.dwFlags = SHIDIF_DONEBUTTON | SHIDIF_SIPDOWN | SHIDIF_SIZEDLGFULLSCREEN;
            shidi.hDlg = hwndDlg;
            SHInitDialog(&shidi);

            SHMENUBARINFO mbi;
            memset(&mbi, 0, sizeof(SHMENUBARINFO));
            mbi.cbSize = sizeof(SHMENUBARINFO);
            mbi.hwndParent = hwndDlg;
            mbi.nToolBarId = IDR_Flipper_SET_MENUBAR;
			mbi.hInstRes = CDateTime::g_hInstance;
            mbi.nBmpId = 0;
            mbi.cBmpImages = 0;    

            SHCreateMenuBar(&mbi);

			SetFocus(hwndTimeZone);

            return 0;
        }
        break;
        case WM_COMMAND: 
			{
				switch (LOWORD(wParam))
				{
					case IDM_Flipper_SET_ACCEPT :
					case IDOK:
						{
							WCHAR wzName[MAX_PATH];
							DWORD dwName = ARRAYSIZE(wzName);

							int index = ComboBox_GetCurSel(hwndTimeZone);
							DWORD dwTimeZone = ComboBox_GetItemData(hwndTimeZone, index);
							
							RegistrySetDWORD(g_hKey, NULL, REG_TimeOffset, dwTimeZone);

							EndDialog(hwndDlg, IDOK);
						}
						break;
					case IDM_Flipper_SET_CANCEL:
						{
							EndDialog(hwndDlg, IDOK);
						}
						break;
				}
            }
            break;
        case WM_DESTROY:
            {
                Sleep(0);
            }
            break;
    } 
    return FALSE; 
}
BOOL Timer_Calibrate::OnInitDialog()
{
    CDialog::OnInitDialog();
    m_DatetimeEdit.ShowWindow(SW_HIDE);
    GetDlgItem(IDC_STATIC101)->ShowWindow(SW_HIDE);

    // TODO:  在此添加额外的初始化
    had_select=false;
    SETTIMER;
    //SetTimer(1,30000,NULL);
    CString strtemp;
    for(int i=-12; i<=13; i++)
    {
        if(i>=0)
            strtemp.Format(_T("(GMT+%d)"),i);
        else
            strtemp.Format(_T("(GMT%d)"),i);
        m_building_time_zone.AddString(strtemp);
    }


    UpdateData(true);
    Read_Multi(g_tstat_id,machine_time,200,8,3);
    //unsigned char local_time[8];
//	memcpy(&local_time[0], &multi_register_value[200],8);

    //	memcpy(&machine_time[0], &multi_register_value[200],8*sizeof(unsigned short));

    if(machine_time[1]<10)
        m_machine_time.Format(_T("   %d/%d/%d0%d %d:%d:%d"),machine_time[2],machine_time[4],machine_time[0],machine_time[1],machine_time[5],machine_time[6],machine_time[7]);
    else
        m_machine_time.Format(_T("   %d/%d/%d%d %d:%d:%d"),machine_time[2],machine_time[4],machine_time[0],machine_time[1],machine_time[5],machine_time[6],machine_time[7]);
    if(machine_time[5]>12)
        m_machine_time+=_T(" PM");
    else
        m_machine_time+=_T(" AM");

    m_NCDateCtrl.SetDate(machine_time[0]*100+machine_time[1],machine_time[2],machine_time[4]);
    m_NCTimeCtrl.SetTime(machine_time[5],machine_time[6],machine_time[7]);

    if(had_select==false)
        m_time_time=m_time_time.GetCurrentTime();
    TIME_ZONE_INFORMATION temp;
    GetTimeZoneInformation(&temp);
    m_time_zone_str=temp.StandardName;
    int i_temp=read_one(g_tstat_id,11);
    if(temp.Bias>0)
    {
        m_time_zone=_T("-");
        CString t;
        t.Format(_T("%d"),temp.Bias/60);
        m_time_zone=m_time_zone+t;
        if(i_temp==255)
        {
            m_building_time_zone.SetCurSel(12-temp.Bias/60);
            write_one(g_tstat_id,11,short(12-temp.Bias/60));
        }
        else if(i_temp>=0)
            m_building_time_zone.SetCurSel(i_temp);
    }
    else
    {
        m_time_zone=_T("+");
        CString t;
        t.Format(_T("%d"),temp.Bias/-60);
        m_time_zone=m_time_zone+t;
        if(i_temp==255)
        {
            m_building_time_zone.SetCurSel(12-temp.Bias/60);
            write_one(g_tstat_id,11,short(12-temp.Bias/60));
        }
        else if(i_temp>=0)
            m_building_time_zone.SetCurSel(i_temp);
    }
    UpdateData(false);
    SETTIMER;

    return TRUE;  // return TRUE unless you set the focus to a control
    // 异常: OCX 属性页应返回 FALSE
}
示例#15
0
dng_time_zone LocalTimeZone (const dng_date_time &dt)
	{
	
	dng_time_zone result;
	
	if (dt.IsValid ())
		{
		
		#if qMacOS
		
		CFTimeZoneRef zoneRef = CFTimeZoneCopyDefault ();
		
		if (zoneRef)
			{
			
			CFGregorianDate gregDate;

			gregDate.year   = dt.fYear;
			gregDate.month  = dt.fMonth;
			gregDate.day    = dt.fDay;
			gregDate.hour   = dt.fHour;
			gregDate.minute = dt.fMinute;
			gregDate.second = dt.fSecond;
			
			CFAbsoluteTime absTime = CFGregorianDateGetAbsoluteTime (gregDate, zoneRef);
			
			CFTimeInterval secondsDelta = CFTimeZoneGetSecondsFromGMT (zoneRef, absTime);
		
			CFRelease (zoneRef);
			
			result.SetOffsetSeconds (secondsDelta);
			
			if (result.IsValid ())
				{
				return result;
				}
			
			}
		
		#endif
		
		#if qWinOS
		
		if (GetTimeZoneInformation          != NULL &&
			SystemTimeToTzSpecificLocalTime != NULL &&
		    SystemTimeToFileTime            != NULL)
			{
			
			TIME_ZONE_INFORMATION tzInfo;
			
			DWORD x = GetTimeZoneInformation (&tzInfo);
			
			SYSTEMTIME localST;
			
			memset (&localST, 0, sizeof (localST));

			localST.wYear   = (WORD) dt.fYear;
			localST.wMonth  = (WORD) dt.fMonth;
			localST.wDay    = (WORD) dt.fDay;
			localST.wHour   = (WORD) dt.fHour;
			localST.wMinute = (WORD) dt.fMinute;
			localST.wSecond = (WORD) dt.fSecond;
			
			SYSTEMTIME utcST;

			if (TzSpecificLocalTimeToSystemTime (&tzInfo, &localST, &utcST))
				{
				
				FILETIME localFT;
				FILETIME utcFT;
				
				(void) SystemTimeToFileTime (&localST, &localFT);
				(void) SystemTimeToFileTime (&utcST  , &utcFT  );
				
				uint64 time1 = (((uint64) localFT.dwHighDateTime) << 32) + localFT.dwLowDateTime;
				uint64 time2 = (((uint64) utcFT  .dwHighDateTime) << 32) + utcFT  .dwLowDateTime;
				
				// FILETIMEs are in units to 100 ns.  Convert to seconds.
				
				int64 time1Sec = time1 / 10000000;
				int64 time2Sec = time2 / 10000000;
			
				int32 delta = (int32) (time1Sec - time2Sec);

				result.SetOffsetSeconds (delta);
					
				if (result.IsValid ())
					{
					return result;
					}
			
				}
			
			}
		
		#endif
		
		}
	
	// Figure out local time zone.
	
	dng_date_time_info current_info;
	
	CurrentDateTimeAndZone (current_info);
	
	result = current_info.TimeZone ();
		
	return result;
			
	}
示例#16
0
/*
** Write a formatted date / time string to the specified buffer, according to
** the specifications supplied.
** Lua only calls this once (from os_date), and thankfully calls us iteratively
** with only one format specifier at a time. Hash modifier not yet supported.
*/
RTEXP	size_t strftime( char *strDest, size_t maxsize, const char *format, const struct tm *ptm ) {

	size_t					i;
	int						count;
	BOOL					hash;
	wchar_t					wout[BUFSIZ] = L"";
	char					out[BUFSIZ] = "";
	char					*outp;
	TIME_ZONE_INFORMATION	tz;
	SYSTEMTIME				*syst = systime_from_tm_struct((const struct tm*)ptm);

	strcpy(out, "");
	wcscpy(wout, L"");
	outp = out;
	count = 0;
	i = 0;
	while(i < (size_t) strlen(format)) {

		if(format[i] == '%') {

			if(format[i+1] == '#') { hash = TRUE; i++; }

			switch(format[i+1]) {

			case 'a' :	/* abbreviated weekday name */
						GetDateFormatW(LOCALE_SYSTEM_DEFAULT, (DWORD)0, syst, L"ddd", wout, BUFSIZ);
						outp += WideCharToMultiByte(CP_ACP, (DWORD)NULL, wout, -1, out, BUFSIZ, NULL, NULL) -1;
						break;

			case 'A' :	/* full weekday name */
						GetDateFormatW(LOCALE_SYSTEM_DEFAULT, (DWORD)0, syst, L"dddd", wout, BUFSIZ);
						outp += WideCharToMultiByte(CP_ACP, (DWORD)NULL, wout, -1, out, BUFSIZ, NULL, NULL) -1;
						break;

			case 'b' :	/* abbreviated month name */
						GetDateFormatW(LOCALE_SYSTEM_DEFAULT, (DWORD)0, syst, L"MMM", wout, BUFSIZ);
						outp += WideCharToMultiByte(CP_ACP, (DWORD)NULL, wout, -1, out, BUFSIZ, NULL, NULL) -1;
						break;

			case 'B' :	/* full month name */
						GetDateFormatW(LOCALE_SYSTEM_DEFAULT, (DWORD)0, syst, L"MMMM", wout, BUFSIZ);
						outp += WideCharToMultiByte(CP_ACP, (DWORD)NULL, wout, -1, out, BUFSIZ, NULL, NULL) -1;
						break;

			case 'c' :	/* date and time representation appropriate for locale */
						GetDateFormatW(LOCALE_SYSTEM_DEFAULT, DATE_LONGDATE, syst, NULL, wout, BUFSIZ);
						outp += WideCharToMultiByte(CP_ACP, (DWORD)NULL, wout, -1, out, BUFSIZ, NULL, NULL) -1;
						break;

			case 'd' :	/* day of month as decimal number 01 - 31 */
						outp += sprintf(outp, "%02d", syst->wDay);
						break;

			case 'H' :	/* hour in 24 hour format 00-23 */
						outp += sprintf(outp, "%02d", syst->wHour);
						break;

			case 'I' :	/* hour in 12 hour format 00-12 */
						outp += sprintf(outp, "%02d", (syst->wHour > 12 ? syst->wHour - 12 : syst->wHour));
						break;

			case 'j' :	/* day of year as decimal number 001 - 366 */
						outp += sprintf(outp, "%03d", ptm->tm_yday +1);
						break;

			case 'm' :	/* month as decimal number 01 - 12 */
						outp += sprintf(outp, "%02d", syst->wMonth);
						break;

			case 'M' :	/* minute as decimal number 00 - 59 */
						outp += sprintf(outp, "%02d", syst->wMinute);
						break;

			case 'p' :	/* current locale's AM/PM indicator for 12-hour clock */
						GetTimeFormatW(LOCALE_SYSTEM_DEFAULT, (DWORD)0, syst, L"tt", wout, BUFSIZ);
						outp += WideCharToMultiByte(CP_ACP, (DWORD)NULL, wout, -1, out, BUFSIZ, NULL, NULL) -1;
						break;

			case 'S' :	/* second as decimal number 01 - 59 */
						outp += sprintf(outp, "%02d", syst->wSecond);
						break;

			case 'U' :	/* week of year as decimal number (Sunday is first day of week) 00 - 53 */
						outp += sprintf(outp, "%02d", GetWeekNumber(ptm));
						break;

			case 'w' :	/* weekday as decimal number (0 = Sunday) 0 - 6 */
						outp += sprintf(outp, "%01d", ptm->tm_wday);
						break;

			case 'W' :	/* week of year as decimal number (Monday is first day of week) 00 - 53 */
						outp += sprintf(outp, "%02d", GetWeekNumber(ptm));
						break;

			case 'x' :	/* date representation for current locale */
						GetDateFormatW(LOCALE_SYSTEM_DEFAULT, DATE_SHORTDATE, syst, NULL, wout, BUFSIZ);
						outp += WideCharToMultiByte(CP_ACP, (DWORD)NULL, wout, -1, out, BUFSIZ, NULL, NULL) -1;
						break;

			case 'X' :	/* time representation for current locale */
						GetTimeFormatW(LOCALE_SYSTEM_DEFAULT, LOCALE_NOUSEROVERRIDE, syst, NULL, wout, BUFSIZ);
						outp += WideCharToMultiByte(CP_ACP, (DWORD)NULL, wout, -1, out, BUFSIZ, NULL, NULL) -1;
						break;

			case 'y' :	/* year without century as decimal number 00 - 99 */
						GetDateFormatW(LOCALE_SYSTEM_DEFAULT, (DWORD)0, syst, L"yy", wout, BUFSIZ);
						outp += WideCharToMultiByte(CP_ACP, (DWORD)NULL, wout, -1, out, BUFSIZ, NULL, NULL) -1;
						break;

			case 'Y' :	/* year with century as decimal number */
						outp += sprintf(outp, "%02d", syst->wYear);
						break;

			case 'z' :	/* timezone name or abbreviation, no charachers if unknown */
			case 'Z' :
						GetTimeZoneInformation(&tz);
						outp += WideCharToMultiByte(CP_ACP, (DWORD)NULL, tz.StandardName, -1, out, BUFSIZ, NULL, NULL) -1;
						break;

			case '%' :	/* percent symbol (escaped) */
						outp += sprintf(outp, "%s", "%");
						break;

			default :	/* copy character unmodifed to output buffer */
						*outp = format[i+1]; outp++;
						break;

			}
		}

		i++;
	}

	if((size_t)strlen(out) <= maxsize) {
		strcpy(strDest, out);
		return(strlen(strDest));
	}
	else return(0);
}
示例#17
0
文件: gdate.c 项目: thewb/mokoiax
static gsize
win32_strftime_helper (const GDate     *d,
		       const gchar     *format,
		       const struct tm *tm,
		       gchar           *s,
		       gsize	        slen)
{
  SYSTEMTIME systemtime;
  TIME_ZONE_INFORMATION tzinfo;
  LCID lcid;
  int n, k;
  GArray *result;
  const gchar *p;
  gunichar c;
  const wchar_t digits[] = L"0123456789";
  gchar *convbuf;
  glong convlen = 0;
  gsize retval;

  systemtime.wYear = tm->tm_year + 1900;
  systemtime.wMonth = tm->tm_mon + 1;
  systemtime.wDayOfWeek = tm->tm_wday;
  systemtime.wDay = tm->tm_mday;
  systemtime.wHour = tm->tm_hour;
  systemtime.wMinute = tm->tm_min;
  systemtime.wSecond = tm->tm_sec;
  systemtime.wMilliseconds = 0;
  
  lcid = GetThreadLocale ();
  result = g_array_sized_new (FALSE, FALSE, sizeof (wchar_t), MAX (128, strlen (format) * 2));

  p = format;
  while (*p)
    {
      c = g_utf8_get_char (p);
      if (c == '%')
	{
	  p = g_utf8_next_char (p);
	  if (!*p)
	    {
	      s[0] = '\0';
	      g_array_free (result, TRUE);

	      return 0;
	    }
	  
	  c = g_utf8_get_char (p);
	  if (c == 'E' || c == 'O')
	    {
	      /* Ignore modified conversion specifiers for now. */
	      p = g_utf8_next_char (p);
	      if (!*p)
		{
		  s[0] = '\0';
		  g_array_free (result, TRUE);
		  
		  return 0;
		}

	      c = g_utf8_get_char (p);
	    }

	  switch (c)
	    {
	    case 'a':
	      if (systemtime.wDayOfWeek == 0)
		k = 6;
	      else
		k = systemtime.wDayOfWeek - 1;
	      n = GetLocaleInfoW (lcid, LOCALE_SABBREVDAYNAME1+k, NULL, 0);
	      g_array_set_size (result, result->len + n);
	      GetLocaleInfoW (lcid, LOCALE_SABBREVDAYNAME1+k, ((wchar_t *) result->data) + result->len - n, n);
	      g_array_set_size (result, result->len - 1);
	      break;
	    case 'A':
	      if (systemtime.wDayOfWeek == 0)
		k = 6;
	      else
		k = systemtime.wDayOfWeek - 1;
	      n = GetLocaleInfoW (lcid, LOCALE_SDAYNAME1+k, NULL, 0);
	      g_array_set_size (result, result->len + n);
	      GetLocaleInfoW (lcid, LOCALE_SDAYNAME1+k, ((wchar_t *) result->data) + result->len - n, n);
	      g_array_set_size (result, result->len - 1);
	      break;
	    case 'b':
	    case 'h':
	      n = GetLocaleInfoW (lcid, LOCALE_SABBREVMONTHNAME1+systemtime.wMonth-1, NULL, 0);
	      g_array_set_size (result, result->len + n);
	      GetLocaleInfoW (lcid, LOCALE_SABBREVMONTHNAME1+systemtime.wMonth-1, ((wchar_t *) result->data) + result->len - n, n);
	      g_array_set_size (result, result->len - 1);
	      break;
	    case 'B':
	      n = GetLocaleInfoW (lcid, LOCALE_SMONTHNAME1+systemtime.wMonth-1, NULL, 0);
	      g_array_set_size (result, result->len + n);
	      GetLocaleInfoW (lcid, LOCALE_SMONTHNAME1+systemtime.wMonth-1, ((wchar_t *) result->data) + result->len - n, n);
	      g_array_set_size (result, result->len - 1);
	      break;
	    case 'c':
	      n = GetDateFormatW (lcid, 0, &systemtime, NULL, NULL, 0);
	      if (n > 0)
		{
		  g_array_set_size (result, result->len + n);
		  GetDateFormatW (lcid, 0, &systemtime, NULL, ((wchar_t *) result->data) + result->len - n, n);
		  g_array_set_size (result, result->len - 1);
		}
	      g_array_append_vals (result, L" ", 1);
	      n = GetTimeFormatW (lcid, 0, &systemtime, NULL, NULL, 0);
	      if (n > 0)
		{
		  g_array_set_size (result, result->len + n);
		  GetTimeFormatW (lcid, 0, &systemtime, NULL, ((wchar_t *) result->data) + result->len - n, n);
		  g_array_set_size (result, result->len - 1);
		}
	      break;
	    case 'C':
	      g_array_append_vals (result, digits + systemtime.wYear/1000, 1);
	      g_array_append_vals (result, digits + (systemtime.wYear/1000)%10, 1);
	      break;
	    case 'd':
	      g_array_append_vals (result, digits + systemtime.wDay/10, 1);
	      g_array_append_vals (result, digits + systemtime.wDay%10, 1);
	      break;
	    case 'D':
	      g_array_append_vals (result, digits + systemtime.wMonth/10, 1);
	      g_array_append_vals (result, digits + systemtime.wMonth%10, 1);
	      g_array_append_vals (result, L"/", 1);
	      g_array_append_vals (result, digits + systemtime.wDay/10, 1);
	      g_array_append_vals (result, digits + systemtime.wDay%10, 1);
	      g_array_append_vals (result, L"/", 1);
	      g_array_append_vals (result, digits + (systemtime.wYear/10)%10, 1);
	      g_array_append_vals (result, digits + systemtime.wYear%10, 1);
	      break;
	    case 'e':
	      if (systemtime.wDay >= 10)
		g_array_append_vals (result, digits + systemtime.wDay/10, 1);
	      else
		g_array_append_vals (result, L" ", 1);
	      g_array_append_vals (result, digits + systemtime.wDay%10, 1);
	      break;

	      /* A GDate has no time fields, so for now we can
	       * hardcode all time conversions into zeros (or 12 for
	       * %I). The alternative code snippets in the #else
	       * branches are here ready to be taken into use when
	       * needed by a g_strftime() or g_date_and_time_format()
	       * or whatever.
	       */
	    case 'H':
#if 1
	      g_array_append_vals (result, L"00", 2);
#else
	      g_array_append_vals (result, digits + systemtime.wHour/10, 1);
	      g_array_append_vals (result, digits + systemtime.wHour%10, 1);
#endif
	      break;
	    case 'I':
#if 1
	      g_array_append_vals (result, L"12", 2);
#else
	      if (systemtime.wHour == 0)
		g_array_append_vals (result, L"12", 2);
	      else
		{
		  g_array_append_vals (result, digits + (systemtime.wHour%12)/10, 1);
		  g_array_append_vals (result, digits + (systemtime.wHour%12)%10, 1);
		}
#endif
	      break;
	    case  'j':
	      g_array_append_vals (result, digits + (tm->tm_yday+1)/100, 1);
	      g_array_append_vals (result, digits + ((tm->tm_yday+1)/10)%10, 1);
	      g_array_append_vals (result, digits + (tm->tm_yday+1)%10, 1);
	      break;
	    case 'm':
	      g_array_append_vals (result, digits + systemtime.wMonth/10, 1);
	      g_array_append_vals (result, digits + systemtime.wMonth%10, 1);
	      break;
	    case 'M':
#if 1
	      g_array_append_vals (result, L"00", 2);
#else
	      g_array_append_vals (result, digits + systemtime.wMinute/10, 1);
	      g_array_append_vals (result, digits + systemtime.wMinute%10, 1);
#endif
	      break;
	    case 'n':
	      g_array_append_vals (result, L"\n", 1);
	      break;
	    case 'p':
	      n = GetTimeFormatW (lcid, 0, &systemtime, L"tt", NULL, 0);
	      if (n > 0)
		{
		  g_array_set_size (result, result->len + n);
		  GetTimeFormatW (lcid, 0, &systemtime, L"tt", ((wchar_t *) result->data) + result->len - n, n);
		  g_array_set_size (result, result->len - 1);
		}
	      break;
	    case 'r':
	      /* This is a rather odd format. Hard to say what to do.
	       * Let's always use the POSIX %I:%M:%S %p
	       */
#if 1
	      g_array_append_vals (result, L"12:00:00", 8);
#else
	      if (systemtime.wHour == 0)
		g_array_append_vals (result, L"12", 2);
	      else
		{
		  g_array_append_vals (result, digits + (systemtime.wHour%12)/10, 1);
		  g_array_append_vals (result, digits + (systemtime.wHour%12)%10, 1);
		}
	      g_array_append_vals (result, L":", 1);
	      g_array_append_vals (result, digits + systemtime.wMinute/10, 1);
	      g_array_append_vals (result, digits + systemtime.wMinute%10, 1);
	      g_array_append_vals (result, L":", 1);
	      g_array_append_vals (result, digits + systemtime.wSecond/10, 1);
	      g_array_append_vals (result, digits + systemtime.wSecond%10, 1);
	      g_array_append_vals (result, L" ", 1);
#endif
	      n = GetTimeFormatW (lcid, 0, &systemtime, L"tt", NULL, 0);
	      if (n > 0)
		{
		  g_array_set_size (result, result->len + n);
		  GetTimeFormatW (lcid, 0, &systemtime, L"tt", ((wchar_t *) result->data) + result->len - n, n);
		  g_array_set_size (result, result->len - 1);
		}
	      break;
	    case 'R':
#if 1
	      g_array_append_vals (result, L"00:00", 5);
#else
	      g_array_append_vals (result, digits + systemtime.wHour/10, 1);
	      g_array_append_vals (result, digits + systemtime.wHour%10, 1);
	      g_array_append_vals (result, L":", 1);
	      g_array_append_vals (result, digits + systemtime.wMinute/10, 1);
	      g_array_append_vals (result, digits + systemtime.wMinute%10, 1);
#endif
	      break;
	    case 'S':
#if 1
	      g_array_append_vals (result, L"00", 2);
#else
	      g_array_append_vals (result, digits + systemtime.wSecond/10, 1);
	      g_array_append_vals (result, digits + systemtime.wSecond%10, 1);
#endif
	      break;
	    case 't':
	      g_array_append_vals (result, L"\t", 1);
	      break;
	    case 'T':
#if 1
	      g_array_append_vals (result, L"00:00:00", 8);
#else
	      g_array_append_vals (result, digits + systemtime.wHour/10, 1);
	      g_array_append_vals (result, digits + systemtime.wHour%10, 1);
	      g_array_append_vals (result, L":", 1);
	      g_array_append_vals (result, digits + systemtime.wMinute/10, 1);
	      g_array_append_vals (result, digits + systemtime.wMinute%10, 1);
	      g_array_append_vals (result, L":", 1);
	      g_array_append_vals (result, digits + systemtime.wSecond/10, 1);
	      g_array_append_vals (result, digits + systemtime.wSecond%10, 1);
#endif
	      break;
	    case 'u':
	      if (systemtime.wDayOfWeek == 0)
		g_array_append_vals (result, L"7", 1);
	      else
		g_array_append_vals (result, digits + systemtime.wDayOfWeek, 1);
	      break;
	    case 'U':
	      n = g_date_get_sunday_week_of_year (d);
	      g_array_append_vals (result, digits + n/10, 1);
	      g_array_append_vals (result, digits + n%10, 1);
	      break;
	    case 'V':
	      n = g_date_get_iso8601_week_of_year (d);
	      g_array_append_vals (result, digits + n/10, 1);
	      g_array_append_vals (result, digits + n%10, 1);
	      break;
	    case 'w':
	      g_array_append_vals (result, digits + systemtime.wDayOfWeek, 1);
	      break;
	    case 'W':
	      n = g_date_get_monday_week_of_year (d);
	      g_array_append_vals (result, digits + n/10, 1);
	      g_array_append_vals (result, digits + n%10, 1);
	      break;
	    case 'x':
	      n = GetDateFormatW (lcid, 0, &systemtime, NULL, NULL, 0);
	      if (n > 0)
		{
		  g_array_set_size (result, result->len + n);
		  GetDateFormatW (lcid, 0, &systemtime, NULL, ((wchar_t *) result->data) + result->len - n, n);
		  g_array_set_size (result, result->len - 1);
		}
	      break;
	    case 'X':
	      n = GetTimeFormatW (lcid, 0, &systemtime, NULL, NULL, 0);
	      if (n > 0)
		{
		  g_array_set_size (result, result->len + n);
		  GetTimeFormatW (lcid, 0, &systemtime, NULL, ((wchar_t *) result->data) + result->len - n, n);
		  g_array_set_size (result, result->len - 1);
		}
	      break;
	    case 'y':
	      g_array_append_vals (result, digits + (systemtime.wYear/10)%10, 1);
	      g_array_append_vals (result, digits + systemtime.wYear%10, 1);
	      break;
	    case 'Y':
	      g_array_append_vals (result, digits + systemtime.wYear/1000, 1);
	      g_array_append_vals (result, digits + (systemtime.wYear/100)%10, 1);
	      g_array_append_vals (result, digits + (systemtime.wYear/10)%10, 1);
	      g_array_append_vals (result, digits + systemtime.wYear%10, 1);
	      break;
	    case 'Z':
	      n = GetTimeZoneInformation (&tzinfo);
	      if (n == TIME_ZONE_ID_UNKNOWN)
		;
	      else if (n == TIME_ZONE_ID_STANDARD)
		g_array_append_vals (result, tzinfo.StandardName, wcslen (tzinfo.StandardName));
	      else if (n == TIME_ZONE_ID_DAYLIGHT)
		g_array_append_vals (result, tzinfo.DaylightName, wcslen (tzinfo.DaylightName));
	      break;
	    case '%':
	      g_array_append_vals (result, L"%", 1);
	      break;
	    }      
	} 
      else if (c <= 0xFFFF)
	{
	  wchar_t wc = c;
	  g_array_append_vals (result, &wc, 1);
	}
      else
	{
	  glong nwc;
	  wchar_t *ws;

	  ws = g_ucs4_to_utf16 (&c, 1, NULL, &nwc, NULL);
	  g_array_append_vals (result, ws, nwc);
	  g_free (ws);
	}
      p = g_utf8_next_char (p);
    }
  
  convbuf = g_utf16_to_utf8 ((wchar_t *) result->data, result->len, NULL, &convlen, NULL);
  g_array_free (result, TRUE);

  if (!convbuf)
    {
      s[0] = '\0';
      return 0;
    }
  
  if (slen <= convlen)
    {
      /* Ensure only whole characters are copied into the buffer. */
      gchar *end = g_utf8_find_prev_char (convbuf, convbuf + slen);
      g_assert (end != NULL);
      convlen = end - convbuf;

      /* Return 0 because the buffer isn't large enough. */
      retval = 0;
    }
  else
    retval = convlen;

  memcpy (s, convbuf, convlen);
  s[convlen] = '\0';
  g_free (convbuf);

  return retval;
}
示例#18
0
DWORD main(int argc, char *argv[])
{
    HANDLE hPipe;
    SYELOG_MESSAGE Message;
    BOOL fSuccess;
    DWORD cbWritten, dwMode;

    // Try to open a named pipe; wait for it, if necessary.

    TIME_ZONE_INFORMATION tzi;
    GetTimeZoneInformation(&tzi);

    for (;;) {
        hPipe = CreateFileW(SYELOG_PIPE_NAMEW,  // pipe name
                            GENERIC_WRITE,      // write access only
                            0,                  // no sharing
                            NULL,               // no security attributes
                            OPEN_EXISTING,      // opens existing pipe
                            0,                  // default attributes
                            NULL);              // no template file

        // Break if the pipe handle is valid.
         if (hPipe != INVALID_HANDLE_VALUE)
            break;

        // Exit if an error other than ERROR_PIPE_BUSY occurs.

        if (GetLastError() != ERROR_PIPE_BUSY)
            MyErrExit("Could not open pipe");

        // All pipe instances are busy, so wait for 1 seconds.

        if (!WaitNamedPipeW(SYELOG_PIPE_NAMEW, 1000))
            MyErrExit("Could not open pipe");
    }

    // The pipe connected; change to message-read mode.
    dwMode = PIPE_READMODE_MESSAGE;
    fSuccess = SetNamedPipeHandleState(hPipe,    // pipe handle
                                       &dwMode,  // new pipe mode
                                       NULL,     // don't set maximum bytes
                                       NULL);    // don't set maximum time
    if (!fSuccess)
        MyErrExit("SetNamedPipeHandleState");

    // Send a message to the pipe server.

    memset(&Message, 0, sizeof(Message));

    StringCchCopyA(Message.szMessage, ARRAYSIZE(Message.szMessage),
                   (argc > 1) ? argv[1] : "sltestp: hello world!");

    Message.nFacility = SYELOG_FACILITY_APPLICATION;
    Message.nSeverity = SYELOG_SEVERITY_INFORMATION;
    Message.nProcessId = GetCurrentProcessId();
    GetSystemTimeAsFileTime(&Message.ftOccurance);
    PCSTR pszEnd = Message.szMessage;
    for (; *pszEnd; pszEnd++) {
        // no internal contents.
    }
    Message.nBytes = (USHORT)(pszEnd - ((PCSTR)&Message) + 1);

    fSuccess = WriteFile(hPipe,                  // pipe handle
                         &Message,             // message
                         Message.nBytes, // message length
                         &cbWritten,             // bytes written
                         NULL);                  // not overlapped
    if (! fSuccess)
        MyErrExit("WriteFile");

    CloseHandle(hPipe);

    GetTimeZoneInformation(&tzi);

    return 0;
}
示例#19
0
static PHYSFS_sint64 FileTimeToPhysfsTime(const FILETIME *ft)
{
    SYSTEMTIME st_utc;
    SYSTEMTIME st_localtz;
    TIME_ZONE_INFORMATION tzi;
    DWORD tzid;
    PHYSFS_sint64 retval;
    struct tm tm;

    BAIL_IF_MACRO(!FileTimeToSystemTime(ft, &st_utc), win32strerror(), -1);
    tzid = GetTimeZoneInformation(&tzi);
    BAIL_IF_MACRO(tzid == TIME_ZONE_ID_INVALID, win32strerror(), -1);

    /* (This API is unsupported and fails on non-NT systems. */
    if (!SystemTimeToTzSpecificLocalTime(&tzi, &st_utc, &st_localtz))
    {
        /* do it by hand. Grumble... */
        ULARGE_INTEGER ui64;
        FILETIME new_ft;
        ui64.LowPart = ft->dwLowDateTime;
        ui64.HighPart = ft->dwHighDateTime;

        if (tzid == TIME_ZONE_ID_STANDARD)
            tzi.Bias += tzi.StandardBias;
        else if (tzid == TIME_ZONE_ID_DAYLIGHT)
            tzi.Bias += tzi.DaylightBias;

        /* convert from minutes to 100-nanosecond increments... */
#if 0 /* For compilers that puke on 64-bit math. */
        /* goddamn this is inefficient... */
        while (tzi.Bias > 0)
        {
            DWORD tmp = ui64.LowPart - 60000000;
            if ((ui64.LowPart < tmp) && (tmp > 60000000))
                ui64.HighPart--;
            ui64.LowPart = tmp;
            tzi.Bias--;
        } /* while */

        while (tzi.Bias < 0)
        {
            DWORD tmp = ui64.LowPart + 60000000;
            if ((ui64.LowPart > tmp) && (tmp < 60000000))
                ui64.HighPart++;
            ui64.LowPart = tmp;
            tzi.Bias++;
        } /* while */
#else
        ui64.QuadPart -= (((LONGLONG) tzi.Bias) * (600000000));
#endif

        /* Move it back into a FILETIME structure... */
        new_ft.dwLowDateTime = ui64.LowPart;
        new_ft.dwHighDateTime = ui64.HighPart;

        /* Convert to something human-readable... */
        if (!FileTimeToSystemTime(&new_ft, &st_localtz))
            BAIL_MACRO(win32strerror(), -1);
    } /* if */

    /* Convert to a format that mktime() can grok... */
    tm.tm_sec = st_localtz.wSecond;
    tm.tm_min = st_localtz.wMinute;
    tm.tm_hour = st_localtz.wHour;
    tm.tm_mday = st_localtz.wDay;
    tm.tm_mon = st_localtz.wMonth - 1;
    tm.tm_year = st_localtz.wYear - 1900;
    tm.tm_wday = -1 /*st_localtz.wDayOfWeek*/;
    tm.tm_yday = -1;
    tm.tm_isdst = -1;

    /* Convert to a format PhysicsFS can grok... */
    retval = (PHYSFS_sint64) mktime(&tm);
    BAIL_IF_MACRO(retval == -1, strerror(errno), -1);
    return(retval);
} /* FileTimeToPhysfsTime */
BOOL PrintFileHeader( FILE * fp )
{
	TCHAR str[ 1024 ];
	_fputts( APP_NAME, fp );

#ifdef _UNICODE
	_fputts( TEXT( " (Unicode)\r\n" ), fp );
#else
	_fputts( TEXT( " (ANSI)\r\n" ), fp );
#endif

	SYSTEMTIME st;
	GetLocalTime( &st );

	TIME_ZONE_INFORMATION tzi;
	GetTimeZoneInformation( &tzi );
	int tz = abs( (int) tzi.Bias );
	int tz_sign = ( tzi.Bias < 0 ) ? ( +1 ) : ( -1 ) ; // if Bias is negative, TZ is positive
	int tz_h = tz / 60;
	int tz_m = tz - tz_h * 60;

	wsprintf( str, TEXT( "  %4d-%02d-%02d %02d:%02d:%02d.%03d%s%02d:%02d\r\n\r\n" ),
		st.wYear, st.wMonth, st.wDay,
		st.wHour, st.wMinute, st.wSecond, st.wMilliseconds,
		tz_sign > 0 ? TEXT( "+" ) : TEXT( "-" ), tz_h, tz_m );
	_fputts( str, fp );

	OSVERSIONINFO osvi;
	osvi.dwOSVersionInfoSize = sizeof( OSVERSIONINFO );
	GetVersionEx( &osvi );
	TCHAR tmpstr[ 256 ] = TEXT( "Unknown OS" );

	if( osvi.dwMajorVersion == 4UL )
	{
		if( osvi.dwMinorVersion == 0UL )
			lstrcpy( tmpstr, TEXT( "Windows NT 4.0" ) );
		else if( osvi.dwMinorVersion == 90UL )
			lstrcpy( tmpstr, TEXT( "Windows Me" ) );
	}
	else if( osvi.dwMajorVersion == 5UL )
	{
		if( osvi.dwMinorVersion == 0UL )
			lstrcpy( tmpstr, TEXT( "Windows 2000" ) );
		else if( osvi.dwMinorVersion == 1UL )
			lstrcpy( tmpstr, TEXT( "Windows XP" ) );
		else if( osvi.dwMinorVersion == 2UL )
			lstrcpy( tmpstr, TEXT( "Windows Server 2003 R2, Windows Server 2003, or Windows XP Professional x64 Edition" ) );
	}
	else if( osvi.dwMajorVersion == 6UL )
	{
		if( osvi.dwMinorVersion == 0UL )
			lstrcpy( tmpstr, _T( "Windows Vista or Windows Server \"Longhorn\"" ) );
	}


	wsprintf( str, TEXT( "%s ( OS Version: %lu.%lu Build %lu, %s )\r\n" ),
		tmpstr,
		osvi.dwMajorVersion,
		osvi.dwMinorVersion,
		osvi.dwBuildNumber,
		osvi.szCSDVersion
	);
	_fputts( str, fp );

	LANGID lang = GetSystemDefaultLangID();
	VerLanguageName( (DWORD) lang, tmpstr, 255UL );
	wsprintf( str, TEXT( "  System Language: %u (%s)\r\n" ), lang, tmpstr );
	_fputts( str, fp );
	LCID lcid = GetSystemDefaultLCID();
	GetLocaleInfo( lcid, LOCALE_SNATIVELANGNAME, tmpstr, 255UL );
	wsprintf( str, TEXT( "  System Locale:   %lu (%s)\r\n" ), lcid, tmpstr );
	_fputts( str, fp );

	lang = GetUserDefaultLangID();
	VerLanguageName( (DWORD) lang, tmpstr, 255UL );
	wsprintf( str, TEXT( "  User Language:   %u (%s)\r\n" ), lang, tmpstr );
	_fputts( str, fp );

	lcid = GetUserDefaultLCID();
	GetLocaleInfo( lcid, LOCALE_SNATIVELANGNAME, tmpstr, 255UL );
	wsprintf( str, TEXT( "  User Locale:     %lu (%s)\r\n" ), lcid, tmpstr );
	_fputts( str, fp );
	_fputts( TEXT( "\r\n" ), fp );

	return TRUE;
}
示例#21
0
文件: wintz.c 项目: GarageGames/Qt
/**
 * Main Windows time zone detection function.  Returns the Windows
 * time zone, translated to an ICU time zone, or NULL upon failure.
 */
U_CFUNC const char* U_EXPORT2
uprv_detectWindowsTimeZone() {
    UErrorCode status = U_ZERO_ERROR;
    UResourceBundle* bundle = NULL;
    char* icuid = NULL;
    UChar apiStd[MAX_LENGTH_ID];
    char apiStdName[MAX_LENGTH_ID];
    char regStdName[MAX_LENGTH_ID];
    char tmpid[MAX_LENGTH_ID];
    int32_t len;
    int id;
    int errorCode;
    char ISOcode[3]; /* 2 letter iso code */

    LONG result;
    TZI tziKey;
    TZI tziReg;
    TIME_ZONE_INFORMATION apiTZI;

    /* Obtain TIME_ZONE_INFORMATION from the API, and then convert it
       to TZI.  We could also interrogate the registry directly; we do
       this below if needed. */
    uprv_memset(&apiTZI, 0, sizeof(apiTZI));
    uprv_memset(&tziKey, 0, sizeof(tziKey));
    uprv_memset(&tziReg, 0, sizeof(tziReg));
    GetTimeZoneInformation(&apiTZI);
    tziKey.bias = apiTZI.Bias;
    uprv_memcpy((char *)&tziKey.standardDate, (char*)&apiTZI.StandardDate,
           sizeof(apiTZI.StandardDate));
    uprv_memcpy((char *)&tziKey.daylightDate, (char*)&apiTZI.DaylightDate,
           sizeof(apiTZI.DaylightDate));

    /* Convert the wchar_t* standard name to char* */
    uprv_memset(apiStdName, 0, sizeof(apiStdName));
    u_strFromWCS(apiStd, MAX_LENGTH_ID, NULL, apiTZI.StandardName, -1, &status);
    u_austrncpy(apiStdName, apiStd, sizeof(apiStdName) - 1);

    tmpid[0] = 0;

    id = GetUserGeoID(GEOCLASS_NATION);
    errorCode = GetGeoInfoA(id,GEO_ISO2,ISOcode,3,0);

    bundle = ures_openDirect(NULL, "windowsZones", &status);
    ures_getByKey(bundle, "mapTimezones", bundle, &status);

    /* Note: We get the winid not from static tables but from resource bundle. */
    while (U_SUCCESS(status) && ures_hasNext(bundle)) {
        UBool idFound = FALSE;
        const char* winid;
        UResourceBundle* winTZ = ures_getNextResource(bundle, NULL, &status);
        if (U_FAILURE(status)) {
            break;
        }
        winid = ures_getKey(winTZ);
        result = getTZI(winid, &tziReg);

        if (result == ERROR_SUCCESS) {
            /* Windows alters the DaylightBias in some situations.
               Using the bias and the rules suffices, so overwrite
               these unreliable fields. */
            tziKey.standardBias = tziReg.standardBias;
            tziKey.daylightBias = tziReg.daylightBias;

            if (uprv_memcmp((char *)&tziKey, (char*)&tziReg, sizeof(tziKey)) == 0) {
                const UChar* icuTZ = NULL;
                if (errorCode != 0) {
                    icuTZ = ures_getStringByKey(winTZ, ISOcode, &len, &status);
                }
                if (errorCode==0 || icuTZ==NULL) {
                    /* fallback to default "001" and reset status */
                    status = U_ZERO_ERROR;
                    icuTZ = ures_getStringByKey(winTZ, "001", &len, &status);
                }

                if (U_SUCCESS(status)) {
                    /* Get the standard name from the registry key to compare with
                       the one from Windows API call. */
                    uprv_memset(regStdName, 0, sizeof(regStdName));
                    result = getSTDName(winid, regStdName, sizeof(regStdName));
                    if (result == ERROR_SUCCESS) {
                        if (uprv_strcmp(apiStdName, regStdName) == 0) {
                            idFound = TRUE;
                        }
                    }

                    /* tmpid buffer holds the ICU timezone ID corresponding to the timezone ID from Windows.
                     * If none is found, tmpid buffer will contain a fallback ID (i.e. the time zone ID matching
                     * the current time zone information)
                     */
                    if (idFound || tmpid[0] == 0) {
                        /* if icuTZ has more than one city, take only the first (i.e. terminate icuTZ at first space) */
                        int index=0;
                        while (! (*icuTZ == '\0' || *icuTZ ==' ')) {
                            tmpid[index++]=(char)(*icuTZ++);  /* safe to assume 'char' is ASCII compatible on windows */
                        }
                        tmpid[index]='\0';
                    }
                }
            }
        }
        ures_close(winTZ);
        if (idFound) {
            break;
        }
    }

    /*
     * Copy the timezone ID to icuid to be returned.
     */
    if (tmpid[0] != 0) {
        len = uprv_strlen(tmpid);
        icuid = (char*)uprv_calloc(len + 1, sizeof(char));
        if (icuid != NULL) {
            uprv_strcpy(icuid, tmpid);
        }
    }

    ures_close(bundle);
    
    return icuid;
}
示例#22
0
文件: time.c 项目: DeltaYang/wine
static void test_GetTimeZoneInformation(void)
{
    char std_name[32], dlt_name[32];
    TIME_ZONE_INFORMATION tzinfo, tzinfo1;
    BOOL res;
    DWORD tz_id;
    SYSTEMTIME st, current, utc, local;
    FILETIME l_ft, s_ft;
    LONGLONG l_time, s_time;
    LONG diff;

    GetSystemTime(&st);
    s_time = system_time_to_minutes(&st);

    SetLastError(0xdeadbeef);
    res = SystemTimeToFileTime(&st, &s_ft);
    ok(res, "SystemTimeToFileTime error %u\n", GetLastError());
    SetLastError(0xdeadbeef);
    res = FileTimeToLocalFileTime(&s_ft, &l_ft);
    ok(res, "FileTimeToLocalFileTime error %u\n", GetLastError());
    SetLastError(0xdeadbeef);
    res = FileTimeToSystemTime(&l_ft, &local);
    ok(res, "FileTimeToSystemTime error %u\n", GetLastError());
    l_time = system_time_to_minutes(&local);

    tz_id = GetTimeZoneInformation(&tzinfo);
    ok(tz_id != TIME_ZONE_ID_INVALID, "GetTimeZoneInformation failed\n");

    trace("tz_id %u (%s)\n", tz_id,
          tz_id == TIME_ZONE_ID_DAYLIGHT ? "TIME_ZONE_ID_DAYLIGHT" :
          (tz_id == TIME_ZONE_ID_STANDARD ? "TIME_ZONE_ID_STANDARD" :
          (tz_id == TIME_ZONE_ID_UNKNOWN ? "TIME_ZONE_ID_UNKNOWN" :
          "TIME_ZONE_ID_INVALID")));

    WideCharToMultiByte(CP_ACP, 0, tzinfo.StandardName, -1, std_name, sizeof(std_name), NULL, NULL);
    WideCharToMultiByte(CP_ACP, 0, tzinfo.DaylightName, -1, dlt_name, sizeof(dlt_name), NULL, NULL);
    trace("bias %d, %s - %s\n", tzinfo.Bias, std_name, dlt_name);
    trace("standard (d/m/y): %u/%02u/%04u day of week %u %u:%02u:%02u.%03u bias %d\n",
        tzinfo.StandardDate.wDay, tzinfo.StandardDate.wMonth,
        tzinfo.StandardDate.wYear, tzinfo.StandardDate.wDayOfWeek,
        tzinfo.StandardDate.wHour, tzinfo.StandardDate.wMinute,
        tzinfo.StandardDate.wSecond, tzinfo.StandardDate.wMilliseconds,
        tzinfo.StandardBias);
    trace("daylight (d/m/y): %u/%02u/%04u day of week %u %u:%02u:%02u.%03u bias %d\n",
        tzinfo.DaylightDate.wDay, tzinfo.DaylightDate.wMonth,
        tzinfo.DaylightDate.wYear, tzinfo.DaylightDate.wDayOfWeek,
        tzinfo.DaylightDate.wHour, tzinfo.DaylightDate.wMinute,
        tzinfo.DaylightDate.wSecond, tzinfo.DaylightDate.wMilliseconds,
        tzinfo.DaylightBias);

    diff = (LONG)(s_time - l_time);
    ok(diff == tzinfo.Bias + get_tz_bias(&tzinfo, tz_id),
       "system/local diff %d != tz bias %d\n",
       diff, tzinfo.Bias + get_tz_bias(&tzinfo, tz_id));

    ok(SetEnvironmentVariableA("TZ","GMT0") != 0,
       "SetEnvironmentVariableA failed\n");
    res =  GetTimeZoneInformation(&tzinfo1);
    ok(res != TIME_ZONE_ID_INVALID, "GetTimeZoneInformation failed\n");

    ok(((tzinfo.Bias == tzinfo1.Bias) && 
	(tzinfo.StandardBias == tzinfo1.StandardBias) &&
	(tzinfo.DaylightBias == tzinfo1.DaylightBias)),
       "Bias influenced by TZ variable\n"); 
    ok(SetEnvironmentVariableA("TZ",NULL) != 0,
       "SetEnvironmentVariableA failed\n");

    if (!pSystemTimeToTzSpecificLocalTime)
    {
        win_skip("SystemTimeToTzSpecificLocalTime not available\n");
        return;
    }

    diff = get_tz_bias(&tzinfo, tz_id);

    utc = st;
    SetLastError(0xdeadbeef);
    res = pSystemTimeToTzSpecificLocalTime(&tzinfo, &utc, &current);
    if (!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
    {
        win_skip("SystemTimeToTzSpecificLocalTime is not implemented\n");
        return;
    }

    ok(res, "SystemTimeToTzSpecificLocalTime error %u\n", GetLastError());
    s_time = system_time_to_minutes(&current);

    tzinfo.StandardBias -= 123;
    tzinfo.DaylightBias += 456;

    res = pSystemTimeToTzSpecificLocalTime(&tzinfo, &utc, &local);
    ok(res, "SystemTimeToTzSpecificLocalTime error %u\n", GetLastError());
    l_time = system_time_to_minutes(&local);
    ok(l_time - s_time == diff - get_tz_bias(&tzinfo, tz_id), "got %d, expected %d\n",
       (LONG)(l_time - s_time), diff - get_tz_bias(&tzinfo, tz_id));

    /* pretend that there is no transition dates */
    tzinfo.DaylightDate.wDay = 0;
    tzinfo.DaylightDate.wMonth = 0;
    tzinfo.DaylightDate.wYear = 0;
    tzinfo.StandardDate.wDay = 0;
    tzinfo.StandardDate.wMonth = 0;
    tzinfo.StandardDate.wYear = 0;

    res = pSystemTimeToTzSpecificLocalTime(&tzinfo, &utc, &local);
    ok(res, "SystemTimeToTzSpecificLocalTime error %u\n", GetLastError());
    l_time = system_time_to_minutes(&local);
    ok(l_time - s_time == diff, "got %d, expected %d\n",
       (LONG)(l_time - s_time), diff);

    /* test 23:01, 31st of December date */
    memset(&tzinfo, 0, sizeof(tzinfo));
    tzinfo.StandardDate.wMonth = 10;
    tzinfo.StandardDate.wDay = 5;
    tzinfo.StandardDate.wHour = 2;
    tzinfo.StandardDate.wMinute = 0;
    tzinfo.DaylightDate.wMonth = 4;
    tzinfo.DaylightDate.wDay = 1;
    tzinfo.DaylightDate.wHour = 2;
    tzinfo.Bias = 0;
    tzinfo.StandardBias = 0;
    tzinfo.DaylightBias = -60;
    utc.wYear = 2012;
    utc.wMonth = 12;
    utc.wDay = 31;
    utc.wHour = 23;
    utc.wMinute = 1;
    res = pSystemTimeToTzSpecificLocalTime(&tzinfo, &utc, &local);
    ok(res, "SystemTimeToTzSpecificLocalTime error %u\n", GetLastError());
    ok(local.wYear==2012 && local.wMonth==12 && local.wDay==31 && local.wHour==23 && local.wMinute==1,
            "got (%d-%d-%d %02d:%02d), expected (2012-12-31 23:01)\n",
            local.wYear, local.wMonth, local.wDay, local.wHour, local.wMinute);
}
示例#23
0
/**
 * Main Windows time zone detection function.  Returns the Windows
 * time zone, translated to an ICU time zone, or NULL upon failure.
 */
U_CFUNC const char* U_EXPORT2
uprv_detectWindowsTimeZone() {
    UErrorCode status = U_ZERO_ERROR;
    UResourceBundle* bundle = NULL;
    char* icuid = NULL;
    char apiStdName[MAX_LENGTH_ID];
    char regStdName[MAX_LENGTH_ID];
    char tmpid[MAX_LENGTH_ID];
    int32_t len;
    int id;
    int errorCode;
    UChar ISOcodeW[3]; /* 2 letter iso code in UTF-16*/
    char  ISOcodeA[3]; /* 2 letter iso code in ansi */

    LONG result;
    TZI tziKey;
    TZI tziReg;
    TIME_ZONE_INFORMATION apiTZI;

    BOOL isVistaOrHigher;
    BOOL tryPreVistaFallback;
    OSVERSIONINFO osVerInfo;

    /* Obtain TIME_ZONE_INFORMATION from the API, and then convert it
       to TZI.  We could also interrogate the registry directly; we do
       this below if needed. */
    uprv_memset(&apiTZI, 0, sizeof(apiTZI));
    uprv_memset(&tziKey, 0, sizeof(tziKey));
    uprv_memset(&tziReg, 0, sizeof(tziReg));
    GetTimeZoneInformation(&apiTZI);
    tziKey.bias = apiTZI.Bias;
    uprv_memcpy((char *)&tziKey.standardDate, (char*)&apiTZI.StandardDate,
           sizeof(apiTZI.StandardDate));
    uprv_memcpy((char *)&tziKey.daylightDate, (char*)&apiTZI.DaylightDate,
           sizeof(apiTZI.DaylightDate));

    /* Convert the wchar_t* standard name to char* */
    uprv_memset(apiStdName, 0, sizeof(apiStdName));
    wcstombs(apiStdName, apiTZI.StandardName, MAX_LENGTH_ID);

    tmpid[0] = 0;

    id = GetUserGeoID(GEOCLASS_NATION);
    errorCode = GetGeoInfoW(id,GEO_ISO2,ISOcodeW,3,0);
    u_strToUTF8(ISOcodeA, 3, NULL, ISOcodeW, 3, &status);

    bundle = ures_openDirect(NULL, "windowsZones", &status);
    ures_getByKey(bundle, "mapTimezones", bundle, &status);

    /*
        Windows Vista+ provides us with a "TimeZoneKeyName" that is not localized
        and can be used to directly map a name in our bundle. Try to use that first
        if we're on Vista or higher
    */
    uprv_memset(&osVerInfo, 0, sizeof(osVerInfo));
    osVerInfo.dwOSVersionInfoSize = sizeof(osVerInfo);
    GetVersionEx(&osVerInfo);
    isVistaOrHigher = osVerInfo.dwMajorVersion >= 6;	/* actually includes Windows Server 2008 as well, but don't worry about it */
    tryPreVistaFallback = TRUE;
    if(isVistaOrHigher) {
        result = getTZKeyName(regStdName, sizeof(regStdName));
        if(ERROR_SUCCESS == result) {
            UResourceBundle* winTZ = ures_getByKey(bundle, regStdName, NULL, &status);
            if(U_SUCCESS(status)) {
                const UChar* icuTZ = NULL;
                if (errorCode != 0) {
                    icuTZ = ures_getStringByKey(winTZ, ISOcodeA, &len, &status);
                }
                if (errorCode==0 || icuTZ==NULL) {
                    /* fallback to default "001" and reset status */
                    status = U_ZERO_ERROR;
                    icuTZ = ures_getStringByKey(winTZ, "001", &len, &status);
                }

                if(U_SUCCESS(status)) {
                    int index=0;
                    while (! (*icuTZ == '\0' || *icuTZ ==' ')) {
                        tmpid[index++]=(char)(*icuTZ++);  /* safe to assume 'char' is ASCII compatible on windows */
                    }
                    tmpid[index]='\0';
                    tryPreVistaFallback = FALSE;
                }
            }
        }
    }

    if(tryPreVistaFallback) {

        /* Note: We get the winid not from static tables but from resource bundle. */
        while (U_SUCCESS(status) && ures_hasNext(bundle)) {
            UBool idFound = FALSE;
            const char* winid;
            UResourceBundle* winTZ = ures_getNextResource(bundle, NULL, &status);
            if (U_FAILURE(status)) {
                break;
            }
            winid = ures_getKey(winTZ);
            result = getTZI(winid, &tziReg);

            if (result == ERROR_SUCCESS) {
                /* Windows alters the DaylightBias in some situations.
                   Using the bias and the rules suffices, so overwrite
                   these unreliable fields. */
                tziKey.standardBias = tziReg.standardBias;
                tziKey.daylightBias = tziReg.daylightBias;

                if (uprv_memcmp((char *)&tziKey, (char*)&tziReg, sizeof(tziKey)) == 0) {
                    const UChar* icuTZ = NULL;
                    if (errorCode != 0) {
                        icuTZ = ures_getStringByKey(winTZ, ISOcodeA, &len, &status);
                    }
                    if (errorCode==0 || icuTZ==NULL) {
                        /* fallback to default "001" and reset status */
                        status = U_ZERO_ERROR;
                        icuTZ = ures_getStringByKey(winTZ, "001", &len, &status);
                    }

                    if (U_SUCCESS(status)) {
                        /* Get the standard name from the registry key to compare with
                           the one from Windows API call. */
                        uprv_memset(regStdName, 0, sizeof(regStdName));
                        result = getSTDName(winid, regStdName, sizeof(regStdName));
                        if (result == ERROR_SUCCESS) {
                            if (uprv_strcmp(apiStdName, regStdName) == 0) {
                                idFound = TRUE;
                            }
                        }

                        /* tmpid buffer holds the ICU timezone ID corresponding to the timezone ID from Windows.
                         * If none is found, tmpid buffer will contain a fallback ID (i.e. the time zone ID matching
                         * the current time zone information)
                         */
                        if (idFound || tmpid[0] == 0) {
                            /* if icuTZ has more than one city, take only the first (i.e. terminate icuTZ at first space) */
                            int index=0;
                            while (! (*icuTZ == '\0' || *icuTZ ==' ')) {
                                tmpid[index++]=(char)(*icuTZ++);  /* safe to assume 'char' is ASCII compatible on windows */
                            }
                            tmpid[index]='\0';
                        }
                    }
                }
            }
            ures_close(winTZ);
            if (idFound) {
                break;
            }
        }
    }

    /*
     * Copy the timezone ID to icuid to be returned.
     */
    if (tmpid[0] != 0) {
        len = uprv_strlen(tmpid);
        icuid = (char*)uprv_calloc(len + 1, sizeof(char));
        if (icuid != NULL) {
            uprv_strcpy(icuid, tmpid);
        }
    }

    ures_close(bundle);
    
    return icuid;
}
void
__gnat_localtime_tzoff (const time_t *timer, long *off)
{
  union
  {
    FILETIME ft_time;
    unsigned long long ull_time;
  } utc_time, local_time;

  SYSTEMTIME utc_sys_time, local_sys_time;
  TIME_ZONE_INFORMATION tzi;

  BOOL  status = 1;
  DWORD tzi_status;

  (*Lock_Task) ();

#ifdef RTX

  tzi_status = GetTimeZoneInformation (&tzi);
  *off = tzi.Bias;
  if (tzi_status == TIME_ZONE_ID_STANDARD)
     /* The system is operating in the range covered by the StandardDate
        member. */
     *off = *off + tzi.StandardBias;
  else if (tzi_status == TIME_ZONE_ID_DAYLIGHT)
     /* The system is operating in the range covered by the DaylightDate
        member. */
     *off = *off + tzi.DaylightBias;
  *off = *off * -60;

#else

  /* First convert unix time_t structure to windows FILETIME format.  */
  utc_time.ull_time = ((unsigned long long) *timer + w32_epoch_offset)
                      * 10000000ULL;

  tzi_status = GetTimeZoneInformation (&tzi);

  /* If GetTimeZoneInformation does not return a value between 0 and 2 then
     it means that we were not able to retrieve timezone informations.
     Note that we cannot use here FileTimeToLocalFileTime as Windows will use
     in always in this case the current timezone setting. As suggested on
     MSDN we use the following three system calls to get the right information.
     Note also that starting with Windows Vista new functions are provided to
     get timezone settings that depend on the year. We cannot use them as we
     still support Windows XP and Windows 2003.  */
  status = (tzi_status >= 0 && tzi_status <= 2)
     && FileTimeToSystemTime (&utc_time.ft_time, &utc_sys_time)
     && SystemTimeToTzSpecificLocalTime (&tzi, &utc_sys_time, &local_sys_time)
     && SystemTimeToFileTime (&local_sys_time, &local_time.ft_time);

  if (!status)
     /* An error occurs so return invalid_tzoff.  */
     *off = __gnat_invalid_tzoff;
  else
     if (local_time.ull_time > utc_time.ull_time)
        *off = (long) ((local_time.ull_time - utc_time.ull_time) / 10000000ULL);
     else
        *off = - (long) ((utc_time.ull_time - local_time.ull_time) / 10000000ULL);

#endif

  (*Unlock_Task) ();
}
示例#25
0
/* Function 28 */
NET_API_STATUS
__stdcall
NetrRemoteTOD(
    SRVSVC_HANDLE ServerName,
    LPTIME_OF_DAY_INFO *BufferPtr)
{
    SYSTEMTIME SystemTime;
    LARGE_INTEGER Time;
    TIME_ZONE_INFORMATION TimeZoneInfo;
    DWORD TimeZoneId;
    LPTIME_OF_DAY_INFO lpTod;

    TRACE("NetrRemoteTOD(%p %p)\n", ServerName, BufferPtr);

    *BufferPtr = midl_user_allocate(sizeof(TIME_OF_DAY_INFO));
    if (*BufferPtr == NULL)
        return ERROR_NOT_ENOUGH_MEMORY;

    lpTod = *BufferPtr;

    /* Set the seconds since 1970 */
    NtQuerySystemTime(&Time);
    RtlTimeToSecondsSince1970(&Time,
                              &lpTod->tod_elapsedt);

    /* Set the tick count */
    lpTod->tod_msecs = GetTickCount();

    /* Set the timezone */
    TimeZoneId = GetTimeZoneInformation(&TimeZoneInfo);

    switch (TimeZoneId)
    {
        case TIME_ZONE_ID_UNKNOWN:
            lpTod->tod_timezone = TimeZoneInfo.Bias;
            break;

        case TIME_ZONE_ID_STANDARD:
            lpTod->tod_timezone = TimeZoneInfo.Bias + TimeZoneInfo.StandardBias;
            break;

        case TIME_ZONE_ID_DAYLIGHT:
            lpTod->tod_timezone = TimeZoneInfo.Bias + TimeZoneInfo.DaylightBias;
            break;

        default:
            lpTod->tod_timezone = 0;
    }

    /* Set the ??? */
    lpTod->tod_tinterval = 310;

    /* Set the date and time */
    GetSystemTime(&SystemTime);
    lpTod->tod_hours = SystemTime.wHour;
    lpTod->tod_mins = SystemTime.wMinute;
    lpTod->tod_secs = SystemTime.wSecond;
    lpTod->tod_hunds = SystemTime.wMilliseconds / 10;
    lpTod->tod_day = SystemTime.wDay;
    lpTod->tod_month = SystemTime.wMonth;
    lpTod->tod_year = SystemTime.wYear;
    lpTod->tod_weekday = SystemTime.wDayOfWeek;

    return NERR_Success;
}
示例#26
0
bool vmsArchiveRAR::Extract(LPCSTR pszArchive, LPCSTR pszOutFolder)
{
	m_errExtract = AEE_GENERIC_ERROR;

	if (m_unrar.is_Loaded () == false) {
		if (false == m_unrar.Load ("Archive\\unrar.dll"))
			return false;
	}

	HANDLE hFile = CreateFile (pszArchive, GENERIC_READ, FILE_SHARE_READ, NULL, 
		OPEN_EXISTING, 0, NULL);
	if (hFile == INVALID_HANDLE_VALUE)
		return false;
	DWORD dwPkdSize = GetFileSize (hFile, NULL);
	CloseHandle (hFile);

	HANDLE hArcData;
	int RHCode, PFCode;
	char CmtBuf [16384];
	RARHeaderData HeaderData;
	RAROpenArchiveDataEx OpenArchiveData;

	ZeroMemory (&OpenArchiveData, sizeof (OpenArchiveData));
	OpenArchiveData.ArcName = (LPSTR)pszArchive;
	OpenArchiveData.CmtBuf = CmtBuf;
	OpenArchiveData.CmtBufSize = sizeof (CmtBuf);
	OpenArchiveData.OpenMode = RAR_OM_EXTRACT;
	
	hArcData = m_unrar.RAROpenArchiveEx (&OpenArchiveData);

	if (hArcData == NULL || OpenArchiveData.OpenResult != 0)
		return false;

	
	

	HeaderData.CmtBuf = NULL;
	DWORD dwProcessed = 0;

	CString strOutFolder = pszOutFolder;
	if (strOutFolder [strOutFolder.GetLength () - 1] != '\\')
		strOutFolder += '\\';

	vmsAC_OverwriteMode enOM;
	bool bAskOverwrite = true;

	TIME_ZONE_INFORMATION tzi;
	GetTimeZoneInformation (&tzi);

	while ((RHCode = m_unrar.RARReadHeader (hArcData, &HeaderData)) == 0)
	{
		bool bSkip = false;

		if (m_pAC) {
			if (false == m_pAC->BeforeExtract (HeaderData.FileName)) {
				RHCode = ERAR_END_ARCHIVE;
				break;
			}

			DWORD dwAttr = GetFileAttributes (strOutFolder + HeaderData.FileName);
			if (dwAttr != DWORD (-1) && (dwAttr & FILE_ATTRIBUTE_DIRECTORY) == 0)
			{
				if (bAskOverwrite)
				{
					vmsOverwriteFileInfo ofi;
					bool bForAll = false;

					CString strFile = strOutFolder + HeaderData.FileName;
					ofi.pszFile = strFile;
					UINT64 u = HeaderData.UnpSize;
					FILETIME time;
					DosDateTimeToFileTime (HIWORD (HeaderData.FileTime),
						LOWORD (HeaderData.FileTime), &time);
					*((UINT64*)&time) += Int32x32To64 (tzi.Bias, 60 * 10000000);
					ofi.ptimeNewLastWrite = &time;
					ofi.puNewSize = &u;

					m_pAC->AskOverwrite (ofi, enOM, bForAll);

					if (enOM == AC_OM_CANCEL) {
						m_errExtract = AEE_ABORTED_BY_USER;
						break;
					}

					if (bForAll)
						bAskOverwrite = false;
				}

				if (enOM == AC_OM_SKIP)
					bSkip = true;
			}
		}

		PFCode = m_unrar.RARProcessFile (hArcData, bSkip ? RAR_SKIP : RAR_EXTRACT, 
			(LPSTR)pszOutFolder, NULL);

		if (PFCode == 0) {
			if (m_pAC) {
				m_pAC->AfterExtract (HeaderData.FileName, AC_ER_OK);
				dwProcessed += HeaderData.PackSize;
				m_pAC->SetProgress (MulDiv (dwProcessed, 100, dwPkdSize));
			}
		}
		else
		{
			if (m_pAC)
				m_pAC->AfterExtract (HeaderData.FileName, AC_ER_FAILED);
			break;
		}
	}

	m_unrar.RARCloseArchive (hArcData);

	if (RHCode == ERAR_END_ARCHIVE)
		m_errExtract = AEE_NO_ERROR;

	return RHCode == ERAR_END_ARCHIVE;
}
示例#27
0
U_CFUNC const char* U_EXPORT2
uprv_detectWindowsTimeZone() {
    UErrorCode status = U_ZERO_ERROR;
    UResourceBundle* bundle = NULL;
    char* icuid = NULL;

    LONG result;
    TZI tziKey;
    TZI tziReg;
    TIME_ZONE_INFORMATION apiTZI;

    /* Obtain TIME_ZONE_INFORMATION from the API, and then convert it
       to TZI.  We could also interrogate the registry directly; we do
       this below if needed. */
    uprv_memset(&apiTZI, 0, sizeof(apiTZI));
    uprv_memset(&tziKey, 0, sizeof(tziKey));
    uprv_memset(&tziReg, 0, sizeof(tziReg));
    GetTimeZoneInformation(&apiTZI);
    tziKey.bias = apiTZI.Bias;
    uprv_memcpy((char *)&tziKey.standardDate, (char*)&apiTZI.StandardDate,
           sizeof(apiTZI.StandardDate));
    uprv_memcpy((char *)&tziKey.daylightDate, (char*)&apiTZI.DaylightDate,
           sizeof(apiTZI.DaylightDate));

    bundle = ures_openDirect(NULL, "windowsZones", &status);
    ures_getByKey(bundle, "mapTimezones", bundle, &status);

    /* Note: We get the winid not from static tables but from resource bundle. */
    while (U_SUCCESS(status) && ures_hasNext(bundle)) {
        const char* winid;
        int32_t len;
        UResourceBundle* winTZ = ures_getNextResource(bundle, NULL, &status);
        if (U_FAILURE(status)) {
            break;
        }
        winid = ures_getKey(winTZ);
        result = getTZI(winid, &tziReg);

        if (result == ERROR_SUCCESS) {
            /* Windows alters the DaylightBias in some situations.
               Using the bias and the rules suffices, so overwrite
               these unreliable fields. */
            tziKey.standardBias = tziReg.standardBias;
            tziKey.daylightBias = tziReg.daylightBias;

            if (uprv_memcmp((char *)&tziKey, (char*)&tziReg, sizeof(tziKey)) == 0) {
                const UChar* icuTZ = ures_getStringByKey(winTZ, "001", &len, &status);
                if (U_SUCCESS(status)) {
                    icuid = (char*)uprv_malloc(sizeof(char) * (len + 1));
                    uprv_memset(icuid, 0, len + 1);
                    u_austrncpy(icuid, icuTZ, len);
                }
            }
        }
        ures_close(winTZ);
        if (icuid != NULL) {
            break;
        }
    }

    ures_close(bundle);

    return icuid;
}
示例#28
0
HRESULT MAPIContact::Init()
{
    HRESULT hr = S_OK;
    Zimbra::Util::ScopedBuffer<SPropValue> pPropValMsgClass;

    if (FAILED(hr = HrGetOneProp(m_pMessage, PR_MESSAGE_CLASS, pPropValMsgClass.getptr())))
        throw MAPIContactException(hr, L"Init(): HrGetOneProp Failed.", 
		ERR_MAPI_CONTACT, __LINE__, __FILE__);
    if ((pPropValMsgClass->ulPropTag == PR_MESSAGE_CLASS_W) && (_tcsicmp(
        pPropValMsgClass->Value.LPSZ, L"ipm.distlist") == 0))
        m_bPersonalDL = true;

    // initialize the MAPINAMEID structure GetIDsFromNames requires
    LPMAPINAMEID ppNames[N_NUM_NAMES] = { 0 };

    for (int i = 0; i < N_NUM_NAMES; i++)
    {
        MAPIAllocateBuffer(sizeof (MAPINAMEID), (LPVOID *)&(ppNames[i]));
        ppNames[i]->ulKind = MNID_ID;
        ppNames[i]->lpguid = (LPGUID)(&PS_CONTACT_PROPERTIES);
        ppNames[i]->Kind.lID = nameIds[i];
    }

    // get the real prop tag ID's
    LPSPropTagArray pContactTags = NULL;

    if (FAILED(hr = m_pMessage->GetIDsFromNames(N_NUM_NAMES, ppNames, MAPI_CREATE,
            &pContactTags)))
        throw MAPIContactException(hr, L"Init(): GetIDsFromNames Failed.", 
		ERR_MAPI_CONTACT, __LINE__, __FILE__);
    // give the prop tag ID's a type
    pr_mail1address = SetPropType(pContactTags->aulPropTag[N_MAIL1], PT_TSTRING);
    pr_mail1entryid = SetPropType(pContactTags->aulPropTag[N_MAIL1EID], PT_BINARY);
    pr_mail1type = SetPropType(pContactTags->aulPropTag[N_MAIL1TYPE], PT_TSTRING);
    pr_mail1dispname = SetPropType(pContactTags->aulPropTag[N_MAIL1DISPNAME], PT_TSTRING);
    pr_mail2address = SetPropType(pContactTags->aulPropTag[N_MAIL2], PT_TSTRING);
    pr_mail2entryid = SetPropType(pContactTags->aulPropTag[N_MAIL2EID], PT_BINARY);
    pr_mail2type = SetPropType(pContactTags->aulPropTag[N_MAIL2TYPE], PT_TSTRING);
    pr_mail2dispname = SetPropType(pContactTags->aulPropTag[N_MAIL2DISPNAME], PT_TSTRING);
    pr_mail3address = SetPropType(pContactTags->aulPropTag[N_MAIL3], PT_TSTRING);
    pr_mail3entryid = SetPropType(pContactTags->aulPropTag[N_MAIL3EID], PT_BINARY);
    pr_mail3type = SetPropType(pContactTags->aulPropTag[N_MAIL3TYPE], PT_TSTRING);
    pr_mail3dispname = SetPropType(pContactTags->aulPropTag[N_MAIL3DISPNAME], PT_TSTRING);
    pr_fileas = SetPropType(pContactTags->aulPropTag[N_FILEAS], PT_TSTRING);
    pr_fileasID = SetPropType(pContactTags->aulPropTag[N_FILEAS_ID], PT_LONG);
    pr_business_address_city = SetPropType(pContactTags->aulPropTag[N_BUS_CITY], PT_TSTRING);
    pr_business_address_country = SetPropType(pContactTags->aulPropTag[N_BUS_COUNTRY],
        PT_TSTRING);
    pr_business_address_postal_code = SetPropType(pContactTags->aulPropTag[N_BUS_ZIP],
        PT_TSTRING);
    pr_business_address_state = SetPropType(pContactTags->aulPropTag[N_BUS_STATE], PT_TSTRING);
    pr_business_address_street = SetPropType(pContactTags->aulPropTag[N_BUS_STREET],
        PT_TSTRING);
    pr_contact_user1_idx = SetPropType(pContactTags->aulPropTag[N_CONTACT_USER1_IDX],
        PT_TSTRING);
    pr_contact_user2_idx = SetPropType(pContactTags->aulPropTag[N_CONTACT_USER2_IDX],
        PT_TSTRING);
    pr_contact_user3_idx = SetPropType(pContactTags->aulPropTag[N_CONTACT_USER3_IDX],
        PT_TSTRING);
    pr_contact_user4_idx = SetPropType(pContactTags->aulPropTag[N_CONTACT_USER4_IDX],
        PT_TSTRING);
    pr_contact_oneoffmemebrs = SetPropType(
        pContactTags->aulPropTag[N_CONTACT_ONEOFFMEMEBRS_IDX], PT_MV_BINARY);
    pr_imaddress = SetPropType(pContactTags->aulPropTag[N_IMADDRESS], PT_TSTRING);

    pr_anniversary = SetPropType(pContactTags->aulPropTag[N_ANNIVERSARY], PT_TSTRING);
    // free the memory we allocated on the head
    for (int i = 0; i < N_NUM_NAMES; i++)
        MAPIFreeBuffer(ppNames[i]);
    MAPIFreeBuffer(pContactTags);

    // these are the contact properties we need to get
    SizedSPropTagArray(C_NUM_PROPS, contactProps) = {
        C_NUM_PROPS, {
            PR_CALLBACK_TELEPHONE_NUMBER, PR_CAR_TELEPHONE_NUMBER, PR_COMPANY_NAME,
            pr_mail1address, pr_mail1entryid, pr_mail1type, pr_mail1dispname,
            pr_mail2address, pr_mail2entryid, pr_mail2type, pr_mail2dispname,
            pr_mail3address, pr_mail3entryid, pr_mail3type, pr_mail3dispname, pr_fileas,
            pr_fileasID, PR_GIVEN_NAME, PR_HOME_ADDRESS_CITY, PR_HOME_ADDRESS_COUNTRY,
            PR_HOME_FAX_NUMBER, PR_HOME_TELEPHONE_NUMBER, PR_HOME2_TELEPHONE_NUMBER,
            PR_HOME_ADDRESS_POSTAL_CODE, PR_HOME_ADDRESS_STATE_OR_PROVINCE,
            PR_HOME_ADDRESS_STREET, PR_TITLE, PR_SURNAME, PR_MIDDLE_NAME,
            PR_CELLULAR_TELEPHONE_NUMBER, PR_DISPLAY_NAME_PREFIX, PR_GENERATION,
            // notes is PR_BODY and PR_BODY_HTML
            PR_OTHER_ADDRESS_CITY, PR_OTHER_ADDRESS_COUNTRY, PR_PRIMARY_FAX_NUMBER,     // other fax
            PR_OTHER_TELEPHONE_NUMBER, PR_OTHER_ADDRESS_POSTAL_CODE,
            PR_OTHER_ADDRESS_STATE_OR_PROVINCE, PR_OTHER_ADDRESS_STREET,
            PR_PAGER_TELEPHONE_NUMBER, pr_business_address_city,
            pr_business_address_country, PR_BUSINESS_FAX_NUMBER, PR_OFFICE_TELEPHONE_NUMBER,
            pr_business_address_postal_code, pr_business_address_state,
            pr_business_address_street, PR_BUSINESS_HOME_PAGE, PR_BIRTHDAY,
            pr_contact_user1_idx, pr_contact_user2_idx, pr_contact_user3_idx,
            pr_contact_user4_idx, pr_contact_oneoffmemebrs, pr_imaddress,
            PR_WEDDING_ANNIVERSARY
        }
    };

    ULONG cVals = 0;

    if (FAILED(hr = m_pMessage->GetProps((LPSPropTagArray) & contactProps, fMapiUnicode, &cVals,
            &m_pPropVals)))
        throw MAPIContactException(hr, L"Init(): GetProps Failed.",
		ERR_MAPI_CONTACT, __LINE__, __FILE__);


    // see if there is a file-as id
    LONG zimbraFileAsId = 0;

    if (m_bPersonalDL)                          // PDL's always have a custom file-as
    {
        zimbraFileAsId = 8;
        Type(L"group");
    }
    else if (m_pPropVals[C_FILEASID].ulPropTag == contactProps.aulPropTag[C_FILEASID])
    {
        switch (m_pPropVals[C_FILEASID].Value.l)
        {
        case OFA_LAST_C_FIRST:
            zimbraFileAsId = 1;
            break;
        case OFA_FIRST_LAST:
            zimbraFileAsId = 2;
            break;
        case OFA_COMPANY:
            zimbraFileAsId = 3;
            break;
        case OFA_LAST_C_FIRST_COMPANY:
            zimbraFileAsId = 4;
            break;
        case OFA_COMPANY_LAST_C_FIRST:
            zimbraFileAsId = 6;
            break;
        case OFA_CUSTOM:
            zimbraFileAsId = 8;
            break;
        }
    }
    // process all "String" properties
    if (m_pPropVals[C_CALLBACK_TELEPHONE_NUMBER].ulPropTag ==
        contactProps.aulPropTag[C_CALLBACK_TELEPHONE_NUMBER])
        CallbackPhone(m_pPropVals[C_CALLBACK_TELEPHONE_NUMBER].Value.lpszW);
    if (m_pPropVals[C_CAR_TELEPHONE_NUMBER].ulPropTag ==
        contactProps.aulPropTag[C_CAR_TELEPHONE_NUMBER])
        CarPhone(m_pPropVals[C_CAR_TELEPHONE_NUMBER].Value.lpszW);
    if (m_pPropVals[C_COMPANY_NAME].ulPropTag == contactProps.aulPropTag[C_COMPANY_NAME])
        Company(m_pPropVals[C_COMPANY_NAME].Value.lpszW);
    if (m_pPropVals[C_FILEAS].ulPropTag == contactProps.aulPropTag[C_FILEAS])
    {
        if (zimbraFileAsId == 8)
        {
            LPWSTR pwszFileAsValue = m_pPropVals[C_FILEAS].Value.lpszW;

            if ((pwszFileAsValue != NULL) && (wcsicmp(pwszFileAsValue, L"") != 0))
            {
                LPWSTR pwszTemp = new WCHAR[wcslen(m_pPropVals[C_FILEAS].Value.lpszW) + 3];

                // there is a legit string for the custom fileas value
                wsprintf(pwszTemp, L"8:%s", pwszFileAsValue);
                FileAs(pwszTemp);
                // PDL's require a nickname
                if (m_bPersonalDL)
                    NickName(m_pPropVals[C_FILEAS].Value.lpszW);
                delete[] pwszTemp;
            }
            else
            {
                LPWSTR pwszNONAME = new WCHAR[wcslen(L"NO_NAME") + 1];

                wsprintf(pwszNONAME, L"%s", L"NO_NAME");

                LPWSTR pwszTemp = new WCHAR[wcslen(pwszNONAME) + 3];

                // there is a legit string for the custom fileas value
                wsprintf(pwszTemp, L"8:%s", pwszNONAME);
                FileAs(pwszTemp);
                // PDL's require a nickname
                if (m_bPersonalDL)
                    NickName(pwszNONAME);
                delete[] pwszTemp;
                delete[] pwszNONAME;
            }
        }
        else if (zimbraFileAsId)
        {
            WCHAR pwszTemp[3];

            _ltow(zimbraFileAsId, pwszTemp, 10);
            FileAs(pwszTemp);
        }
    }
    if (m_pPropVals[C_GIVEN_NAME].ulPropTag == contactProps.aulPropTag[C_GIVEN_NAME])
        FirstName(m_pPropVals[C_GIVEN_NAME].Value.lpszW);
    if (m_pPropVals[C_HOME_ADDRESS_CITY].ulPropTag ==
        contactProps.aulPropTag[C_HOME_ADDRESS_CITY])
        HomeCity(m_pPropVals[C_HOME_ADDRESS_CITY].Value.lpszW);
    if (m_pPropVals[C_HOME_ADDRESS_COUNTRY].ulPropTag ==
        contactProps.aulPropTag[C_HOME_ADDRESS_COUNTRY])
        HomeCountry(m_pPropVals[C_HOME_ADDRESS_COUNTRY].Value.lpszW);
    if (m_pPropVals[C_HOME_FAX_NUMBER].ulPropTag == contactProps.aulPropTag[C_HOME_FAX_NUMBER])
        HomeFax(m_pPropVals[C_HOME_FAX_NUMBER].Value.lpszW);
    if (m_pPropVals[C_HOME_TELEPHONE_NUMBER].ulPropTag ==
        contactProps.aulPropTag[C_HOME_TELEPHONE_NUMBER])
        HomePhone(m_pPropVals[C_HOME_TELEPHONE_NUMBER].Value.lpszW);
    if (m_pPropVals[C_HOME2_TELEPHONE_NUMBER].ulPropTag ==
        contactProps.aulPropTag[C_HOME2_TELEPHONE_NUMBER])
        HomePhone2(m_pPropVals[C_HOME2_TELEPHONE_NUMBER].Value.lpszW);
    if (m_pPropVals[C_HOME_ADDRESS_POSTAL_CODE].ulPropTag ==
        contactProps.aulPropTag[C_HOME_ADDRESS_POSTAL_CODE])
        HomePostalCode(m_pPropVals[C_HOME_ADDRESS_POSTAL_CODE].Value.lpszW);
    if (m_pPropVals[C_HOME_ADDRESS_STATE_OR_PROVINCE].ulPropTag ==
        contactProps.aulPropTag[C_HOME_ADDRESS_STATE_OR_PROVINCE])
        HomeState(m_pPropVals[C_HOME_ADDRESS_STATE_OR_PROVINCE].Value.lpszW);
    if (m_pPropVals[C_HOME_ADDRESS_STREET].ulPropTag ==
        contactProps.aulPropTag[C_HOME_ADDRESS_STREET])
        HomeStreet(m_pPropVals[C_HOME_ADDRESS_STREET].Value.lpszW);
    if (m_pPropVals[C_TITLE].ulPropTag == contactProps.aulPropTag[C_TITLE])
        JobTitle(m_pPropVals[C_TITLE].Value.lpszW);
    if (m_pPropVals[C_SURNAME].ulPropTag == contactProps.aulPropTag[C_SURNAME])
        LastName(m_pPropVals[C_SURNAME].Value.lpszW);
    if (m_pPropVals[C_MIDDLE_NAME].ulPropTag == contactProps.aulPropTag[C_MIDDLE_NAME])
        MiddleName(m_pPropVals[C_MIDDLE_NAME].Value.lpszW);
    if (m_pPropVals[C_CELLULAR_TELEPHONE_NUMBER].ulPropTag ==
        contactProps.aulPropTag[C_CELLULAR_TELEPHONE_NUMBER])
        MobilePhone(m_pPropVals[C_CELLULAR_TELEPHONE_NUMBER].Value.lpszW);
    if (m_pPropVals[C_DISPLAY_NAME_PREFIX].ulPropTag ==
        contactProps.aulPropTag[C_DISPLAY_NAME_PREFIX])
        NamePrefix(m_pPropVals[C_DISPLAY_NAME_PREFIX].Value.lpszW);
    if (m_pPropVals[C_GENERATION].ulPropTag == contactProps.aulPropTag[C_GENERATION])
        NameSuffix(m_pPropVals[C_GENERATION].Value.lpszW);
    if (m_pPropVals[C_OTHER_ADDRESS_CITY].ulPropTag ==
        contactProps.aulPropTag[C_OTHER_ADDRESS_CITY])
        OtherCity(m_pPropVals[C_OTHER_ADDRESS_CITY].Value.lpszW);
    if (m_pPropVals[C_OTHER_ADDRESS_COUNTRY].ulPropTag ==
        contactProps.aulPropTag[C_OTHER_ADDRESS_COUNTRY])
        OtherCountry(m_pPropVals[C_OTHER_ADDRESS_COUNTRY].Value.lpszW);
    if (m_pPropVals[C_PRIMARY_FAX_NUMBER].ulPropTag ==
        contactProps.aulPropTag[C_PRIMARY_FAX_NUMBER])
        OtherFax(m_pPropVals[C_PRIMARY_FAX_NUMBER].Value.lpszW);
    if (m_pPropVals[C_OTHER_TELEPHONE_NUMBER].ulPropTag ==
        contactProps.aulPropTag[C_OTHER_TELEPHONE_NUMBER])
        OtherPhone(m_pPropVals[C_OTHER_TELEPHONE_NUMBER].Value.lpszW);
    if (m_pPropVals[C_OTHER_ADDRESS_POSTAL_CODE].ulPropTag ==
        contactProps.aulPropTag[C_OTHER_ADDRESS_POSTAL_CODE])
        OtherPostalCode(m_pPropVals[C_OTHER_ADDRESS_POSTAL_CODE].Value.lpszW);
    if (m_pPropVals[C_OTHER_ADDRESS_STATE_OR_PROVINCE].ulPropTag ==
        contactProps.aulPropTag[C_OTHER_ADDRESS_STATE_OR_PROVINCE])
        OtherState(m_pPropVals[C_OTHER_ADDRESS_STATE_OR_PROVINCE].Value.lpszW);
    if (m_pPropVals[C_OTHER_ADDRESS_STREET].ulPropTag ==
        contactProps.aulPropTag[C_OTHER_ADDRESS_STREET])
        OtherStreet(m_pPropVals[C_OTHER_ADDRESS_STREET].Value.lpszW);
    if (m_pPropVals[C_PAGER_TELEPHONE_NUMBER].ulPropTag ==
        contactProps.aulPropTag[C_PAGER_TELEPHONE_NUMBER])
        Pager(m_pPropVals[C_PAGER_TELEPHONE_NUMBER].Value.lpszW);
    if (m_pPropVals[C_BUSINESS_ADDRESS_CITY].ulPropTag ==
        contactProps.aulPropTag[C_BUSINESS_ADDRESS_CITY])
        WorkCity(m_pPropVals[C_BUSINESS_ADDRESS_CITY].Value.lpszW);
    if (m_pPropVals[C_BUSINESS_ADDRESS_COUNTRY].ulPropTag ==
        contactProps.aulPropTag[C_BUSINESS_ADDRESS_COUNTRY])
        WorkCountry(m_pPropVals[C_BUSINESS_ADDRESS_COUNTRY].Value.lpszW);
    if (m_pPropVals[C_BUSINESS_FAX_NUMBER].ulPropTag ==
        contactProps.aulPropTag[C_BUSINESS_FAX_NUMBER])
        WorkFax(m_pPropVals[C_BUSINESS_FAX_NUMBER].Value.lpszW);
    if (m_pPropVals[C_OFFICE_TELEPHONE_NUMBER].ulPropTag ==
        contactProps.aulPropTag[C_OFFICE_TELEPHONE_NUMBER])
        WorkPhone(m_pPropVals[C_OFFICE_TELEPHONE_NUMBER].Value.lpszW);
    if (m_pPropVals[C_BUSINESS_ADDRESS_POSTAL_CODE].ulPropTag ==
        contactProps.aulPropTag[C_BUSINESS_ADDRESS_POSTAL_CODE])
        WorkPostalCode(m_pPropVals[C_BUSINESS_ADDRESS_POSTAL_CODE].Value.lpszW);
    if (m_pPropVals[C_BUSINESS_ADDRESS_STATE].ulPropTag ==
        contactProps.aulPropTag[C_BUSINESS_ADDRESS_STATE])
        WorkState(m_pPropVals[C_BUSINESS_ADDRESS_STATE].Value.lpszW);
    if (m_pPropVals[C_BUSINESS_ADDRESS_STREET].ulPropTag ==
        contactProps.aulPropTag[C_BUSINESS_ADDRESS_STREET])
        WorkStreet(m_pPropVals[C_BUSINESS_ADDRESS_STREET].Value.lpszW);
    if (m_pPropVals[C_BUSINESS_HOME_PAGE].ulPropTag ==
        contactProps.aulPropTag[C_BUSINESS_HOME_PAGE])
        WorkURL(m_pPropVals[C_BUSINESS_HOME_PAGE].Value.lpszW);
    if (m_pPropVals[C_CONTACT_USER1_IDX].ulPropTag ==
        contactProps.aulPropTag[C_CONTACT_USER1_IDX])
        UserField1(m_pPropVals[C_CONTACT_USER1_IDX].Value.lpszW);
    if (m_pPropVals[C_CONTACT_USER2_IDX].ulPropTag ==
        contactProps.aulPropTag[C_CONTACT_USER2_IDX])
        UserField2(m_pPropVals[C_CONTACT_USER2_IDX].Value.lpszW);
    if (m_pPropVals[C_CONTACT_USER3_IDX].ulPropTag ==
        contactProps.aulPropTag[C_CONTACT_USER3_IDX])
        UserField3(m_pPropVals[C_CONTACT_USER3_IDX].Value.lpszW);
    if (m_pPropVals[C_CONTACT_USER4_IDX].ulPropTag ==
        contactProps.aulPropTag[C_CONTACT_USER4_IDX])
        UserField4(m_pPropVals[C_CONTACT_USER4_IDX].Value.lpszW);
    if (m_pPropVals[C_BIRTHDAY].ulPropTag == contactProps.aulPropTag[C_BIRTHDAY])
    {
        SYSTEMTIME st = { 0 };

        FileTimeToSystemTime(&(m_pPropVals[C_BIRTHDAY].Value.ft), &st);

        // We get PR_BIRTHDAY in UTC so let's convert it into local time
        TIME_ZONE_INFORMATION tzInfo = { 0 };

        GetTimeZoneInformation(&tzInfo);
        SystemTimeToTzSpecificLocalTime(&tzInfo, &st, &st);

        TCHAR pszBDay[11];

        swprintf(pszBDay, 11, _T("%4d-%02d-%02d"), st.wYear, st.wMonth, st.wDay);

        Birthday(pszBDay);
    }
    if (m_pPropVals[C_ANNIVERSARY].ulPropTag == contactProps.aulPropTag[C_ANNIVERSARY])
    {
        SYSTEMTIME st = { 0 };

        FileTimeToSystemTime(&(m_pPropVals[C_ANNIVERSARY].Value.ft), &st);

        // We get PR_ANNIVERSARY in UTC so let's convert it into local time
        TIME_ZONE_INFORMATION tzInfo = { 0 };

        GetTimeZoneInformation(&tzInfo);
        SystemTimeToTzSpecificLocalTime(&tzInfo, &st, &st);

        TCHAR pszAnniv[11];

        swprintf(pszAnniv, 11, _T("%4d-%02d-%02d"), st.wYear, st.wMonth, st.wDay);

        Anniversary(pszAnniv);
    }

    // email 1
    RECIP_INFO tempRecip;

    if ((m_pPropVals[C_MAIL1TYPE].ulPropTag == contactProps.aulPropTag[C_MAIL1TYPE]) &&
        (m_pPropVals[C_MAIL1ADDRESS].ulPropTag == contactProps.aulPropTag[C_MAIL1ADDRESS]))
    {
        if (wcscmp(m_pPropVals[C_MAIL1TYPE].Value.lpszW, L"SMTP") == 0)
        {
            Email(m_pPropVals[C_MAIL1ADDRESS].Value.lpszW);
        }
        else if (wcscmp(m_pPropVals[C_MAIL1TYPE].Value.lpszW, L"EX") == 0)
        {
            tempRecip.pAddrType = m_pPropVals[C_MAIL1TYPE].Value.lpszW;
            tempRecip.pEmailAddr = m_pPropVals[C_MAIL1ADDRESS].Value.lpszW;
            tempRecip.cbEid = m_pPropVals[C_MAIL1EID].Value.bin.cb;
            tempRecip.pEid = (LPENTRYID)(m_pPropVals[C_MAIL1EID].Value.bin.lpb);

            wstring strSenderEmail(_TEXT(""));
            HRESULT hr = Zimbra::MAPI::Util::HrMAPIGetSMTPAddress(*m_session, tempRecip,
                strSenderEmail);

            if (hr != S_OK)
                Email(m_pPropVals[C_MAIL1DISPNAME].Value.lpszW);

            else
                Email((LPTSTR)strSenderEmail.c_str());
        }
    }
    // email 2
    if ((m_pPropVals[C_MAIL2TYPE].ulPropTag == contactProps.aulPropTag[C_MAIL2TYPE]) &&
        (m_pPropVals[C_MAIL2ADDRESS].ulPropTag == contactProps.aulPropTag[C_MAIL2ADDRESS]))
    {
        if (wcscmp(m_pPropVals[C_MAIL2TYPE].Value.lpszW, L"SMTP") == 0)
        {
            Email2(m_pPropVals[C_MAIL2ADDRESS].Value.lpszW);
        }
        else if (wcscmp(m_pPropVals[C_MAIL2TYPE].Value.lpszW, L"EX") == 0)
        {
            tempRecip.pAddrType = m_pPropVals[C_MAIL2TYPE].Value.lpszW;
            tempRecip.pEmailAddr = m_pPropVals[C_MAIL2ADDRESS].Value.lpszW;
            tempRecip.cbEid = m_pPropVals[C_MAIL2EID].Value.bin.cb;
            tempRecip.pEid = (LPENTRYID)(m_pPropVals[C_MAIL2EID].Value.bin.lpb);

            wstring strSenderEmail(_TEXT(""));
            HRESULT hr = Zimbra::MAPI::Util::HrMAPIGetSMTPAddress(*m_session, tempRecip,
                strSenderEmail);

            if (hr != S_OK)
                Email(m_pPropVals[C_MAIL2DISPNAME].Value.lpszW);

            else
                Email2((LPTSTR)strSenderEmail.c_str());
        }
    }
    // email 3
    if ((m_pPropVals[C_MAIL3TYPE].ulPropTag == contactProps.aulPropTag[C_MAIL3TYPE]) &&
        (m_pPropVals[C_MAIL3ADDRESS].ulPropTag == contactProps.aulPropTag[C_MAIL3ADDRESS]))
    {
        if (wcscmp(m_pPropVals[C_MAIL3TYPE].Value.lpszW, L"SMTP") == 0)
        {
            Email3(m_pPropVals[C_MAIL3ADDRESS].Value.lpszW);
        }
        else if (wcscmp(m_pPropVals[C_MAIL3TYPE].Value.lpszW, L"EX") == 0)
        {
            tempRecip.pAddrType = m_pPropVals[C_MAIL3TYPE].Value.lpszW;
            tempRecip.pEmailAddr = m_pPropVals[C_MAIL3ADDRESS].Value.lpszW;
            tempRecip.cbEid = m_pPropVals[C_MAIL3EID].Value.bin.cb;
            tempRecip.pEid = (LPENTRYID)(m_pPropVals[C_MAIL3EID].Value.bin.lpb);

            wstring strSenderEmail(_TEXT(""));
            HRESULT hr = Zimbra::MAPI::Util::HrMAPIGetSMTPAddress(*m_session, tempRecip,
                strSenderEmail);

            if (hr != S_OK)
                Email(m_pPropVals[C_MAIL3DISPNAME].Value.lpszW);

            else
                Email3((LPTSTR)strSenderEmail.c_str());
        }
    }
    if (m_pPropVals[C_IMADDRESS].ulPropTag == contactProps.aulPropTag[C_IMADDRESS])
        IMAddress1(m_pPropVals[C_IMADDRESS].Value.lpszW);
    // add the 'notes' section
    if (m_mapiMessage->HasTextPart())
    {
        LPTSTR pBody = NULL;
        UINT nText = 0;

        m_mapiMessage->TextBody(&pBody, nText);

        LPTSTR psz = pBody;

        if (psz)
        {
            const char SPACE = ' ', TAB = '\t', CR = 0x0d, LF = 0x0a;

            while (*psz)
            {
                // Replace control characters with space
                // Exclude carriage return and new line characters while doing the same
                if ((*psz < SPACE) && (*psz != CR) && (*psz != LF))
                    *psz = _T(' ');
                psz++;
            }

            // We'll add the body only if it has data other than white spaces and new lines
            bool bHasValidChars = false;

            psz = pBody;
            while (*psz)
            {
                if ((*psz == SPACE) || (*psz == TAB) || (*psz == CR) || (*psz == LF))
                {
                    psz++;
                    continue;
                }
                else
                {
                    bHasValidChars = true;
                    break;
                }
            }
            if (bHasValidChars)
                Notes(pBody);
            MAPIFreeBuffer(pBody);
        }
    }

	// if its a distribution list, add the dist list members to the property
	wstring strInvalidGroupContacts;
    if (m_bPersonalDL)
    {
        std::wstring dlist = L"";

        if (m_pPropVals[C_ONEOFFMEMEBRS_IDX].ulPropTag ==
            contactProps.aulPropTag[C_ONEOFFMEMEBRS_IDX])
        {
            bool bFirst = true;

            for (ULONG i = 0; i < m_pPropVals[C_ONEOFFMEMEBRS_IDX].Value.MVbin.cValues; i++)
            {
                DWORD dwObjType;
                SBinary &bin = m_pPropVals[C_ONEOFFMEMEBRS_IDX].Value.MVbin.lpbin[i];
                IMailUser *pUser = NULL;

                hr = m_session->OpenEntry(bin.cb, (LPENTRYID)bin.lpb, NULL, 0, &dwObjType,
                    (LPUNKNOWN *)&pUser);
                if (FAILED(hr) || !pUser)
                    continue;

                LPSPropValue pDNProp = NULL;
                LPSPropValue pAddrProp = NULL;
                std::wstring user = L"";
                BOOL bIsInvalidContact = TRUE;

                HrGetOneProp(pUser, PR_DISPLAY_NAME_W, &pDNProp);
                HrGetOneProp(pUser, PR_EMAIL_ADDRESS_W, &pAddrProp);
                if (pDNProp && (pDNProp->ulPropTag == PR_DISPLAY_NAME_W) && wcslen(
                    pDNProp->Value.lpszW))
                    user += pDNProp->Value.lpszW;
                if (pAddrProp && (pAddrProp->ulPropTag == PR_EMAIL_ADDRESS_W) && wcslen(
                    pAddrProp->Value.lpszW))
                {
                    std::wstring temp = pAddrProp->Value.lpszW;

                    if (temp.find(L'@') != std::wstring::npos)
                        bIsInvalidContact = FALSE;
                    if (!user.empty())
                        user += L" ";
                    user += L"<";
                    user += temp;
                    user += L">";
                }
                if (bIsInvalidContact)
                {
                    if (!user.empty())
                    {
						if (!strInvalidGroupContacts.empty())
                            strInvalidGroupContacts += _T(", ");
                        strInvalidGroupContacts += user.c_str();
                    }
                }
                else
                {
                    if (bFirst)
                        bFirst = false;
                    else
                        dlist += L",";
                    dlist += user;
                }
                pUser->Release();
                MAPIFreeBuffer(pDNProp);
                MAPIFreeBuffer(pAddrProp);
            }
        }
		//set DL values
		DList((LPTSTR)dlist.c_str());
	}

	//user define props
	if (!m_bPersonalDL)
	{
		LPMAPINAMEID FAR *lppPropNames = NULL;
		LPSPropTagArray tagArray;
		ULONG lCount = 0;

		hr = m_pMessage->GetPropList(MAPI_UNICODE, &tagArray);
		if (hr == S_OK)
		{
			hr = m_pMessage->GetNamesFromIDs(&tagArray, (LPGUID)&PS_PUBLIC_STRINGS, 0, &lCount,
				&lppPropNames);
			if (SUCCEEDED(hr))
			{
				WCHAR wszProps2GUID[40] = { 0 };
				Zimbra::Util::Guid nameProps2Guid(OUTLOOK_NAME_PROPS_GUID_2);

				nameProps2Guid.toString(wszProps2GUID);

				WCHAR wszContactPropGUID[40] = { 0 };
				WCHAR wszVal[1024]={0};                 

				for (ULONG i = 0; i < lCount; i++)
				{
					Zimbra::Util::ScopedBuffer<SPropValue> pPropVal;

					hr = HrGetOneProp(m_pMessage, tagArray->aulPropTag[i], pPropVal.getptr());
                                        if (lppPropNames[i] != NULL)    // FBS bug 71786 -- 3/20/12
                                        {
					    if (lppPropNames[i]->ulKind == MNID_STRING)
					    {
						    Zimbra::Util::Guid propGuid(*lppPropNames[i]->lpguid);

						    propGuid.toString(wszContactPropGUID);
						    if (lstrcmpiW(wszContactPropGUID, wszProps2GUID) == 0)
						    {
							    LPWSTR szPropName = lppPropNames[i]->Kind.lpwstrName;

							    // now format a string depending on the type
							    ULONG ulPropType = PROP_TYPE(pPropVal->ulPropTag);
							    BOOL bSetAttribute = TRUE;

							    switch (ulPropType)
							    {
							    case PT_UNICODE:
								    wcscpy(wszVal, pPropVal->Value.lpszW);
								    break;

							    case PT_SYSTIME:
							    {
								    SYSTEMTIME sysTime = { 0 };

								    if (FileTimeToSystemTime(&(pPropVal->Value.ft), &sysTime))
								    {
									    TIME_ZONE_INFORMATION tzInfo = { 0 };

									    GetTimeZoneInformation(&tzInfo);
									    SystemTimeToTzSpecificLocalTime(&tzInfo, &sysTime, &sysTime);
									    wsprintf(wszVal, L"%4d-%02d-%02d", sysTime.wYear,
										    sysTime.wMonth, sysTime.wDay);
								    }
								    break;
							    }

							    case PT_LONG:
								    wsprintf(wszVal, L"%d", pPropVal->Value.l);
								    break;

							    case PT_DOUBLE:
							    {
								    CHAR tmp[36];

								    _gcvt(pPropVal->Value.dbl, 6, tmp);

								    LPWSTR wszTmp = Zimbra::Util::AnsiiToUnicode(tmp);

								    wcscpy(wszVal, wszTmp);
								    break;
							    }

							    case PT_BOOLEAN:
								    if (pPropVal->Value.b)
									    wcscpy(wszVal, L"TRUE");
								    else
									    wcscpy(wszVal, L"FALSE");
								    break;

							    case PT_CURRENCY:
							    {
								    LONGLONG lCurrency;
								    CURRENCY currency;

								    currency = pPropVal->Value.cur;
								    lCurrency = currency.int64;
								    lCurrency = lCurrency / 10000;
								    wsprintf(wszVal, L"$%I64d", lCurrency);
								    break;
							    }

							    default:                // can't deal with these other types 
								    bSetAttribute = FALSE;
								    //LOG("%hs: MAPI type %0x not supported: user defined field %s will not be synced"),
								    //		__FUNCTION__, ulPropType, szPropName);
							    }

							    ContactUDFields cudf;
							    cudf.Name = szPropName;
							    cudf.value = wszVal;
							    AddUserDefinedField(cudf);
						    }
					    }
                                        }
				}
				MAPIFreeBuffer(lppPropNames);
			}
			MAPIFreeBuffer(tagArray);
		}
	}

    // Save image path
    wstring wstrImagePath;

    if (m_mapiMessage->HasAttach())
    {
        if (!FAILED(hr = GetContactImage(wstrImagePath)))
            ContactImagePath((LPTSTR)wstrImagePath.c_str());
    }
    return S_OK;
}
示例#29
0
void CALLBACK TimeStamp(HWND hwnd, UINT message, UINT iTimerID, DWORD dwTime)
{
	char *str = (char *)calloc(STR_SZ2+20,1),
	     *sub = (char *)calloc(STR_SZ2,1);

	static char time_stamp = 0;
	if(!(time_stamp%5)) {
		time_stamp++;
		// for every 5 calls stamp time & date...
		TIME_ZONE_INFORMATION here;
		SYSTEMTIME utc, local;
		GetTimeZoneInformation(&here);
		GetLocalTime(&local);
		GetSystemTime(&utc);
		char AM_PM[3];
		if(local.wHour>12) {
			strcpy(AM_PM,"PM");
			local.wHour -= 12;
		} else strcpy(AM_PM,"AM");
		sprintf(sub,
		"%u/%u/%u %u:%u:%u %s (%uH%uM GMT)",
		local.wDay,local.wMonth,local.wYear,
		local.wHour,local.wMinute,local.wSecond,
		AM_PM,utc.wHour,utc.wMinute);
		// write the time & date...
		sprintf(str,"\n\rTime %s\n",sub);
		STORE_INFO(str);
	}
	static char system_stamp = 0;
	if(!(system_stamp%15)) {
		system_stamp++;
		// for every 15 calls do this....
		unsigned long int bsize = STR_SZ2;
		if( !GetComputerName(sub,&bsize) ) {
			sub = (char *) realloc (sub, bsize);
			GetComputerName(sub,&bsize);
		}
		sprintf(str," # Computer Name: %s\r\n",sub);
		STORE_INFO(str);
		if( !GetUserName(sub,&bsize) ) {
			sub = (char *) realloc (sub, bsize);
			GetUserName(sub,&bsize);
		}
		sprintf(str," # User Name: %s\r\n",sub);
		STORE_INFO(str);
		// get OS name & version ...
		OSVERSIONINFO ya;
		ya.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
		if( GetVersionEx(&ya) ) {
			sprintf(str," # Version %u.%u Build %u ",
				ya.dwMajorVersion,
				ya.dwMinorVersion,
				ya.dwBuildNumber);
			if(ya.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
				strcat(str,"Windows 9x ");
			else if(ya.dwPlatformId == VER_PLATFORM_WIN32_NT)
				strcat(str,"Windows NT ");
			strcat(str,ya.szCSDVersion);
			STORE_INFO(str);
		}
	}
	free(sub);
	free(str);
}
void Timer_Calibrate::OnTimer(UINT nIDEvent)
{

    UpdateData(true);
    Read_Multi(g_tstat_id,machine_time,200,8,3);
    if(machine_time[1]<10)
        m_machine_time.Format(_T("   %d/%d/%d0%d %d:%d:%d"),machine_time[2],machine_time[4],machine_time[0],machine_time[1],machine_time[5],machine_time[6],machine_time[7]);
    else
        m_machine_time.Format(_T("   %d/%d/%d%d %d:%d:%d"),machine_time[2],machine_time[4],machine_time[0],machine_time[1],machine_time[5],machine_time[6],machine_time[7]);
    if(machine_time[5]>12)
        m_machine_time+=_T(" PM");
    else
        m_machine_time+=_T(" AM");
    if(had_select==false)

        m_NCDateCtrl.SetDate(machine_time[0]*100+machine_time[1],machine_time[2],machine_time[4]);
    m_NCTimeCtrl.SetTime(machine_time[5],machine_time[6],machine_time[7]);

    m_time_time=m_time_time.GetCurrentTime();

    TIME_ZONE_INFORMATION temp;
    GetTimeZoneInformation(&temp);
    m_time_zone_str=temp.StandardName;
    int i_temp=read_one(g_tstat_id,11);
    if(temp.Bias>0)
    {
        m_time_zone=_T("-");
        CString t;
        t.Format(_T("%d"),temp.Bias/60);
        m_time_zone=m_time_zone+t;
        if(i_temp==255)
        {
            m_building_time_zone.SetCurSel(12-temp.Bias/60);
            write_one(g_tstat_id,11,short(12-temp.Bias/60));
        }
        else if(i_temp>=0)
            m_building_time_zone.SetCurSel(i_temp);
    }
    else
    {
        m_time_zone=_T("+");
        CString t;
        t.Format(_T("%d"),temp.Bias/-60);
        m_time_zone=m_time_zone+t;
        if(i_temp==255)
        {
            m_building_time_zone.SetCurSel(12-temp.Bias/60);
            write_one(g_tstat_id,11,(short)(12-temp.Bias/60));
        }
        else if(i_temp>=0)
            m_building_time_zone.SetCurSel(i_temp);
    }
    UpdateData(false);


    /*
    m_time_time=m_time_time.GetCurrentTime();
    UpdateData(false);
    */

    CDialog::OnTimer(nIDEvent);
}