void MAPIAppointment::SetEndDate(FILETIME ft, bool bAllday)
{
    SYSTEMTIME st, localst;
    BOOL bUseLocal = false;

    FileTimeToSystemTime(&ft, &st);

    if (bAllday)    // if AllDay appt, subtract one from the end date for Zimbra friendliness
    {
	double dat = -1;
	if (SystemTimeToVariantTime(&st, &dat))
	{
	    dat -= 1;
	    VariantTimeToSystemTime(dat, &st);
	}
    }
    else
    {
	if ((m_bIsRecurring) || (m_iExceptionType == NORMAL_EXCEPTION))
	{
	    TIME_ZONE_INFORMATION localTimeZone = {0};
	    //GetTimeZoneInformation(&localTimeZone);	
		pInvTz->PopulateTimeZoneInfo(localTimeZone);
	    bUseLocal = SystemTimeToTzSpecificLocalTime(&localTimeZone, &st, &localst);
	}
    }
    m_pEndDate = (bUseLocal) ? Zimbra::Util::FormatSystemTime(localst, FALSE, TRUE)
			     : Zimbra::Util::FormatSystemTime(st, TRUE, TRUE);
}
Ejemplo n.º 2
0
static DATE QDateTimeToDATE(const QDateTime &dt)
{
    if (!dt.isValid() || dt.isNull())
        return 949998;
    
    SYSTEMTIME stime;
    memset(&stime, 0, sizeof(stime));
    QDate date = dt.date();
    QTime time = dt.time();
    if (date.isValid() && !date.isNull()) {
        stime.wDay = date.day();
        stime.wMonth = date.month();
        stime.wYear = date.year();
    }
    if (time.isValid() && !time.isNull()) {
        stime.wMilliseconds = time.msec();
        stime.wSecond = time.second();
        stime.wMinute = time.minute();
        stime.wHour = time.hour();
    }
    
    double vtime;
    SystemTimeToVariantTime(&stime, &vtime);
    
    return vtime;
}
Ejemplo n.º 3
0
STDMETHODIMP CLogMessage::get_ReceivedDate(DATE* pVal)
{
TRY_CATCH
	SYSTEMTIME sysTime = static_cast<SYSTEMTIME>(m_receivedDate);
	SystemTimeToVariantTime(&sysTime,pVal);
	return S_OK;
CATCH_LOG_COMERROR()
}
Ejemplo n.º 4
0
BOOL CADORecordset::SetFieldValue(LPCTSTR lpFieldName, SYSTEMTIME time)
{
    double          vtime;
	_variant_t      vtFld;
  
    SystemTimeToVariantTime(&time,&vtime);
    vtFld.vt = VT_DATE;
	vtFld.date = vtime;
	return PutFieldValue(lpFieldName, vtFld);
}
Ejemplo n.º 5
0
DATE GetLocalVariantDateTime()
{
  // Get the current date/time in the local time zone
  SYSTEMTIME st;
  GetLocalTime(&st);

  // Convert the date/time to VariantTime
  DATE time = 0;
  _VERIFYE(SystemTimeToVariantTime(&st, &time));
  return time;
}
Ejemplo n.º 6
0
void PowerDocsExtHelper::PopulateDocPropertiesForVersion(DOCSObjects::IVersionPtr pVer,WSDocNonCom& wsDoc,const DOCSObjects::IProfilePtr& pProf)
{
	try
	{
		DOCSObjects::IColumnsPtr pCols	= pProf->GetColumns();
		// have stuck this value in the type and class members (?)
 		//DOCSObjects::IColumnPtr pCol = pCols->GetItem( _variant_t( "DOCNAME" ));
		
		CStdString csDescription = GetColumnValue(pCols, _T("DOCNAME"));
		wsDoc.SetDescription(csDescription);
		
		wsDoc.SetExtension(GetDocumentExtension(pProf));
			
		wsDoc.SetType(GetColumnValue(pCols, _T("APP_ID")));
		wsDoc.SetClass(GetColumnValue(pCols, _T("TYPE_ID")));
		wsDoc.SetAuthor(GetColumnValue(pCols, _T("AUTHOR_ID")));
		wsDoc.SetOperator(GetColumnValue(pCols, _T("TYPIST_ID")));
		
		long lDocNum = pProf->GetDocNumber();
		CStdString sLibName ( pProf->GetLibrary()->GetName() );
		CStdString sVersion (pVer->GetVersionLabel());

		CStdString sDocID;
 		sDocID.Format(_T("PowerDocs://%s/%d/%s"), sLibName.c_str(), lDocNum, sVersion.c_str());
		wsDoc.SetDocId(sDocID);

		if(wsDoc.GetLocalFile().length()>0)
		{
			WIN32_FIND_DATA w32Data;
			CStdString sLocalFile = wsDoc.GetLocalFile();
			
			HANDLE hFile = FindFirstFile(sLocalFile, &w32Data);
			
			wsDoc.SetFileSizehigh(w32Data.nFileSizeHigh);
			wsDoc.SetFileSizeLow(w32Data.nFileSizeLow);
			
			
			SYSTEMTIME sysTime;
			FileTimeToSystemTime(&w32Data.ftLastWriteTime, &sysTime);
			DATE dTime;
			SystemTimeToVariantTime(&sysTime, &dTime);
			
			wsDoc.SetModifiedTime(dTime);
			FindClose(hFile);
		}
		
	}
	catch(_com_error&)
	{		
 		LOG_WS_ERROR(_T("::PopulateDocProperties threw excpetion") );
	}
	
	return;
}
Ejemplo n.º 7
0
DATE GetVariantDateTime()
{
  // Get the current date/time in Universal Coordinated Time (UCT)
  SYSTEMTIME st;
  GetSystemTime(&st);

  // Convert the date/time to VariantTime
  DATE time = 0;
  _VERIFYE(SystemTimeToVariantTime(&st, &time));
  return time;
}
Ejemplo n.º 8
0
BOOL CADORecordset::SetFieldValue(int nIndex, SYSTEMTIME time)
{
    double          vtime;
	_variant_t      vtFld;
    SystemTimeToVariantTime(&time,&vtime);
	vtFld.vt = VT_DATE;
	vtFld.date = vtime;
	_variant_t vtIndex;
	vtIndex.vt = VT_I2;
	vtIndex.iVal = nIndex;
	return PutFieldValue(vtIndex, vtFld);
}
Ejemplo n.º 9
0
CString CAdminPageThreadWnd::GetDate()
{
  DATE date;
  if (FAILED(m_spEvent->get_Time(&date)))
    return CString();

  // Format the date as a string
  SYSTEMTIME sysTime;
  VariantTimeToLocalTime(date, &sysTime);
  SystemTimeToVariantTime(&sysTime, &date);
  CComBSTR bstr;
  VarBstrFromDate(date, GetThreadLocale(), LOCALE_NOUSEROVERRIDE, &bstr);
  return CString(bstr.m_str,bstr.Length());
}
Ejemplo n.º 10
0
BOOL SystemTimeToVariantTimeWithMilliseconds (/*input*/ SYSTEMTIME st, /*output*/double *dVariantTime)
{
    WORD wMilliSeconds = st.wMilliseconds; // save the milli second information

    st.wMilliseconds = 0; // pass 0 milliseconds to the function and get
                          // the converted value without milliseconds
    double dWithoutms;
    if (!SystemTimeToVariantTime(&st, &dWithoutms))
        return FALSE;

    // manually convert the millisecond information into variant
    // fraction and add it to system converted value
    *dVariantTime = dWithoutms + (ONETHOUSANDMILLISECONDS * wMilliSeconds / 1000.0);
    return TRUE;
}
Ejemplo n.º 11
0
DATE GetLocalVariantTime()
{
  // Get the current date/time in Universal Coordinated Time (UCT)
  SYSTEMTIME st;
  GetLocalTime(&st);

  // Clear the date fields (30 December, 1899 by convention)
  st.wYear = 1899;
  st.wMonth = 12;
  st.wDay = 30;

  // Convert the time to VariantTime
  DATE time = 0;
  _VERIFYE(SystemTimeToVariantTime(&st, &time));
  return time;
}
Ejemplo n.º 12
0
DATE GetLocalVariantDate()
{
  // Get the current date/time in Universal Coordinated Time (UCT)
  SYSTEMTIME st;
  GetLocalTime(&st);

  // Clear the time fields (00:00 midnight by convention)
  st.wHour = 0;
  st.wMinute = 0;
  st.wSecond = 0;
  st.wMilliseconds = 0;

  // Convert the date to VariantTime
  DATE time = 0;
  _VERIFYE(SystemTimeToVariantTime(&st, &time));
  return time;
}
Ejemplo n.º 13
0
void CSiteItem::AddSiteItemToDatabase()
{
	ATLASSERT(m_parent);

	try
	{
		double lastWriteTime;
		SYSTEMTIME systime;
		FileTimeToSystemTime(&m_wfd.ftLastWriteTime, &systime);
		SystemTimeToVariantTime(&systime, &lastWriteTime);

		ADODB::_RecordsetPtr files("ADODB.RecordSet");
		files->Open(
			L"files",
			_variant_t(m_pWebSite->m_connstr),
			ADODB::adOpenForwardOnly, ADODB::adLockOptimistic, ADODB::adCmdTable);

		files->AddNew();
		files->Fields->Item[_variant_t(L"parent_id")]->Value = (long)((CSiteDir*)m_parent)->m_dbid;
		files->Fields->Item[_variant_t(L"type")]->Value = (long)m_type;
		files->Fields->Item[_variant_t(L"filename")]->Value = m_wfd.cFileName;
		files->Fields->Item[_variant_t(L"file_size")]->Value = (long)m_wfd.nFileSizeLow;
		files->Fields->Item[_variant_t(L"file_date")]->Value = (double)lastWriteTime;

		files->Update();
		files->Close();

		_variant_t	va;

		va.Clear();
		ADODB::_RecordsetPtr recordset;
		recordset = m_pWebSite->m_siteDataConnection->Execute(L"SELECT MAX(id) AS id FROM files", &va, ADODB::adCmdText);
	//	recordset = m_pWebSite->m_siteDataConnection->Execute(L"SELECT @@IDENTITY AS id", &va, ADODB::adCmdText);

		m_dbid = recordset->Fields->Item[_bstr_t(L"id")]->Value.lVal;
	}
	catch (_com_error &e)
	{
		DbError(e);
	}
}
Ejemplo n.º 14
0
HRESULT
ceFileTimeToDate(
    IN FILETIME const *pft,
    OUT DATE *pDate)
{
    SYSTEMTIME st;
    HRESULT hr = S_OK;

    if (!FileTimeToSystemTime(pft, &st))
    {
        hr = ceHLastError();
        _JumpError(hr, error, "FileTimeToSystemTime");
    }
    if (!SystemTimeToVariantTime(&st, pDate))
    {
        hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA);
        _JumpError(hr, error, "SystemTimeToVariantTime");
    }

error:
    return(hr);
}
Ejemplo n.º 15
0
WXDLLEXPORT bool wxConvertVariantToOle(const wxVariant& variant, VARIANTARG& oleVariant)
{
    VariantInit(&oleVariant);
    if (variant.IsNull())
    {
        oleVariant.vt = VT_NULL;
        return true;
    }

    wxString type(variant.GetType());


    if (type == wxT("long"))
    {
        oleVariant.vt = VT_I4;
        oleVariant.lVal = variant.GetLong() ;
    }
    else if (type == wxT("char"))
    {
        oleVariant.vt=VT_I1;            // Signed Char
        oleVariant.cVal=variant.GetChar();
    }
    else if (type == wxT("double"))
    {
        oleVariant.vt = VT_R8;
        oleVariant.dblVal = variant.GetDouble();
    }
    else if (type == wxT("bool"))
    {
        oleVariant.vt = VT_BOOL;
        oleVariant.boolVal = variant.GetBool();
    }
    else if (type == wxT("string"))
    {
        wxString str( variant.GetString() );
        oleVariant.vt = VT_BSTR;
        oleVariant.bstrVal = wxConvertStringToOle(str);
    }
#if wxUSE_DATETIME
    else if (type == wxT("datetime"))
    {
        wxDateTime date( variant.GetDateTime() );
        oleVariant.vt = VT_DATE;

        SYSTEMTIME st;
        date.GetAsMSWSysTime(&st);

        SystemTimeToVariantTime(&st, &oleVariant.date);
    }
#endif
    else if (type == wxT("void*"))
    {
        oleVariant.vt = VT_DISPATCH;
        oleVariant.pdispVal = (IDispatch*) variant.GetVoidPtr();
    }
    else if (type == wxT("list") || type == wxT("stringlist"))
    {
        oleVariant.vt = VT_VARIANT | VT_ARRAY;

        SAFEARRAY *psa;
        SAFEARRAYBOUND saBound;
        VARIANTARG *pvargBase;
        VARIANTARG *pvarg;
        int i, j;

        int iCount = variant.GetCount();

        saBound.lLbound = 0;
        saBound.cElements = iCount;

        psa = SafeArrayCreate(VT_VARIANT, 1, &saBound);
        if (psa == NULL)
            return false;

        SafeArrayAccessData(psa, (void**)&pvargBase);

        pvarg = pvargBase;
        for (i = 0; i < iCount; i++)
        {
            // copy each string in the list of strings
            wxVariant eachVariant(variant[i]);
            if (!wxConvertVariantToOle(eachVariant, * pvarg))
            {
                // memory failure:  back out and free strings alloc'ed up to
                // now, and then the array itself.
                pvarg = pvargBase;
                for (j = 0; j < i; j++)
                {
                    SysFreeString(pvarg->bstrVal);
                    pvarg++;
                }
                SafeArrayDestroy(psa);
                return false;
            }
            pvarg++;
        }

        SafeArrayUnaccessData(psa);

        oleVariant.parray = psa;
    }
    else
    {
        oleVariant.vt = VT_NULL;
        return false;
    }
    return true;
}
Ejemplo n.º 16
0
HRESULT FindUsers(IDirectorySearch *pContainerToSearch,  //IDirectorySearch pointer to Partitions container.
		 LPOLESTR szFilter, //Filter for finding specific crossrefs.
                            //NULL returns all attributeSchema objects.
         LPOLESTR *pszPropertiesToReturn, //Properties to return for crossRef objects found
					                    //NULL returns all set properties.
		 unsigned long ulNumPropsToReturn, // Number of property strings in pszPropertiesToReturn
		 BOOL bIsVerbose //TRUE means all properties for the found objects are displayed.
		                 //FALSE means only the RDN
							)
{
	if (!pContainerToSearch)
		return E_POINTER;
    //Create search filter
	LPOLESTR pszSearchFilter = new OLECHAR[MAX_PATH*2];
	if ( !pszSearchFilter )
			return E_OUTOFMEMORY;
	wchar_t szFormat[] = L"(&(objectClass=user)(objectCategory=person)%s)";

	// Check the buffer first
	 if ( IS_BUFFER_ENOUGH(MAX_PATH*2, szFormat, szFilter) > 0 )
	 {
		 //Add the filter.
          swprintf_s(pszSearchFilter, MAX_PATH*2, szFormat,szFilter);
	 }
	 else
	 {
		 wprintf(L"The filter is too large for buffer, aborting...");
		 delete [] pszSearchFilter; 
         return FALSE;
	 }
	
    

    //Specify subtree search
	ADS_SEARCHPREF_INFO SearchPrefs;
	SearchPrefs.dwSearchPref = ADS_SEARCHPREF_SEARCH_SCOPE;
	SearchPrefs.vValue.dwType = ADSTYPE_INTEGER;
	SearchPrefs.vValue.Integer = ADS_SCOPE_SUBTREE;
    DWORD dwNumPrefs = 1;

	// COL for iterations
	LPOLESTR pszColumn = NULL;    
	ADS_SEARCH_COLUMN col;
    HRESULT hr;
    
    // Interface Pointers
    IADs    *pObj = NULL;
    IADs	* pIADs = NULL;

    // Handle used for searching
    ADS_SEARCH_HANDLE hSearch = NULL;
	
	// Set the search preference
    hr = pContainerToSearch->SetSearchPreference( &SearchPrefs, dwNumPrefs);
    if (FAILED(hr))
	{
		delete [] pszSearchFilter;
        return hr;
	}

	LPOLESTR pszBool = NULL;
	DWORD dwBool;
	PSID pObjectSID = NULL;
	LPOLESTR szSID = NULL;
	LPOLESTR szDSGUID = new WCHAR [39];
	LPGUID pObjectGUID = NULL;
	FILETIME filetime;
	SYSTEMTIME systemtime;
	DATE date;
	VARIANT varDate;
	LARGE_INTEGER liValue;
	LPOLESTR *pszPropertyList = NULL;
	LPOLESTR pszNonVerboseList[] = {L"name",L"distinguishedName"};
	unsigned long ulNonVbPropsCount = 2;

	LPOLESTR szName = new OLECHAR[MAX_PATH];
	LPOLESTR szDN = new OLECHAR[MAX_PATH];

	if ( !szName || !szDN )
	{
		delete [] pszSearchFilter;
		if ( szDN )
			delete [] szDN;
		if ( szName  )
			delete [] szName ;

		return E_OUTOFMEMORY;
	}

	int iCount = 0;
	DWORD x = 0L;



	if (!bIsVerbose)
	{
		 //Return non-verbose list properties only
         hr = pContainerToSearch->ExecuteSearch(pszSearchFilter,
		                          pszNonVerboseList,
								  ulNonVbPropsCount,
								  &hSearch
								  );
	}
	else
	{
		if (!pszPropertiesToReturn)
		{
			//Return all properties.
			hr = pContainerToSearch->ExecuteSearch(pszSearchFilter,
		                          NULL,
								  -1L,
								  &hSearch
								  );
		}
		else
		{
			//specified subset.
		    pszPropertyList = pszPropertiesToReturn;
		   //Return specified properties
		   hr = pContainerToSearch->ExecuteSearch(pszSearchFilter,
		                          pszPropertyList,
								  sizeof(pszPropertyList)/sizeof(LPOLESTR),
								  &hSearch
								  );
		}
	}
 	if ( SUCCEEDED(hr) )
	{    
    // Call IDirectorySearch::GetNextRow() to retrieve the next row 
    //of data
	  hr = pContainerToSearch->GetFirstRow( hSearch);
	  if (SUCCEEDED(hr))
	  {
        while( hr != S_ADS_NOMORE_ROWS )
		{
			//Keep track of count.
			iCount++;
			if (bIsVerbose)
			  wprintf(L"----------------------------------\n");
            // loop through the array of passed column names,
            // print the data for each column

			while( pContainerToSearch->GetNextColumnName( hSearch, &pszColumn ) != S_ADS_NOMORE_COLUMNS )
            {
                hr = pContainerToSearch->GetColumn( hSearch, pszColumn, &col );
			    if ( SUCCEEDED(hr) )
			    {
		            // Print the data for the column and free the column
				  if(bIsVerbose)
				  {
			        // Get the data for this column
				    wprintf(L"%s\n",col.pszAttrName);
					switch (col.dwADsType)
					{
						case ADSTYPE_DN_STRING:
                          for (x = 0; x< col.dwNumValues; x++)
						  {
							  wprintf(L"  %s\r\n",col.pADsValues[x].DNString);
						  }
						  break;
						case ADSTYPE_CASE_EXACT_STRING:	    
						case ADSTYPE_CASE_IGNORE_STRING:	    
						case ADSTYPE_PRINTABLE_STRING:	    
						case ADSTYPE_NUMERIC_STRING:	        
						case ADSTYPE_TYPEDNAME:	            
						case ADSTYPE_FAXNUMBER:	            
						case ADSTYPE_PATH:	                
						case ADSTYPE_OBJECT_CLASS:
						  for (x = 0; x< col.dwNumValues; x++)
						  {
							  wprintf(L"  %s\r\n",col.pADsValues[x].CaseIgnoreString);
						  }
						  break;
						case ADSTYPE_BOOLEAN:
						  for (x = 0; x< col.dwNumValues; x++)
						  {
							  dwBool = col.pADsValues[x].Boolean;
							  pszBool = dwBool ? L"TRUE" : L"FALSE";
							  wprintf(L"  %s\r\n",pszBool);
						  }
						  break;
						case ADSTYPE_INTEGER:
					      for (x = 0; x< col.dwNumValues; x++)
						  {
							  wprintf(L"  %d\r\n",col.pADsValues[x].Integer);
						  }
						  break;
						case ADSTYPE_OCTET_STRING:
						    if ( _wcsicmp(col.pszAttrName,L"objectSID") == 0 )
							{
						      for (x = 0; x< col.dwNumValues; x++)
							  {
								  pObjectSID = (PSID)(col.pADsValues[x].OctetString.lpValue);
								  //Convert SID to string.
								  ConvertSidToStringSid(pObjectSID, &szSID);
								  wprintf(L"  %s\r\n",szSID);
								  LocalFree(szSID);
							  }
							}
						    else if ( (_wcsicmp(col.pszAttrName,L"objectGUID") == 0) )
							{
						      for (x = 0; x< col.dwNumValues; x++)
							  {
								//Cast to LPGUID
								pObjectGUID = (LPGUID)(col.pADsValues[x].OctetString.lpValue);
								//Convert GUID to string.
								::StringFromGUID2(*pObjectGUID, szDSGUID, 39); 
								//Print the GUID
								wprintf(L"  %s\r\n",szDSGUID);
							  }
							}
							else
							  wprintf(L"  Value of type Octet String. No Conversion.");
						    break;
						case ADSTYPE_UTC_TIME:
						  for (x = 0; x< col.dwNumValues; x++)
						  {
							systemtime = col.pADsValues[x].UTCTime;
							if (SystemTimeToVariantTime(&systemtime,
														&date) != 0) 
							{
								//Pack in variant.vt
								varDate.vt = VT_DATE;
								varDate.date = date;
								VariantChangeType(&varDate,&varDate,VARIANT_NOVALUEPROP,VT_BSTR);
							    wprintf(L"  %s\r\n",varDate.bstrVal);
								VariantClear(&varDate);
							}
							else
								wprintf(L"Could not convert UTC-Time.\n");
						  }
						  break;
						case ADSTYPE_LARGE_INTEGER:
						  for (x = 0; x< col.dwNumValues; x++)
						  {
						    liValue = col.pADsValues[x].LargeInteger;
							filetime.dwLowDateTime = liValue.LowPart;
							filetime.dwHighDateTime = liValue.HighPart;
							if((filetime.dwHighDateTime==0) && (filetime.dwLowDateTime==0))
							{
								wprintf(L"  No value set.\n");
							}
							else
							{
								//Check for properties of type LargeInteger that represent time
								//if TRUE, then convert to variant time.
								if ((0==wcscmp(L"accountExpires", col.pszAttrName))|
									(0==wcscmp(L"badPasswordTime", col.pszAttrName))||
									(0==wcscmp(L"lastLogon", col.pszAttrName))||
									(0==wcscmp(L"lastLogoff", col.pszAttrName))||
									(0==wcscmp(L"lockoutTime", col.pszAttrName))||
									(0==wcscmp(L"pwdLastSet", col.pszAttrName))
								   )
								{
									//Handle special case for Never Expires where low part is -1
									if (filetime.dwLowDateTime==-1)
									{
										wprintf(L"  Never Expires.\n");
									}
									else
									{
										if (FileTimeToLocalFileTime(&filetime, &filetime) != 0) 
										{
											if (FileTimeToSystemTime(&filetime,
																 &systemtime) != 0)
											{
												if (SystemTimeToVariantTime(&systemtime,
																			&date) != 0) 
												{
													//Pack in variant.vt
													varDate.vt = VT_DATE;
													varDate.date = date;
													VariantChangeType(&varDate,&varDate,VARIANT_NOVALUEPROP,VT_BSTR);
													wprintf(L"  %s\r\n",varDate.bstrVal);
													VariantClear(&varDate);
												}
												else
												{
													wprintf(L"  FileTimeToVariantTime failed\n");
												}
											}
											else
											{
												wprintf(L"  FileTimeToSystemTime failed\n");
											}

										}
										else
										{
											wprintf(L"  FileTimeToLocalFileTime failed\n");
										}
									}
								}
								else
								{
									//Print the LargeInteger.
									wprintf(L"  high: %d low: %d\r\n",filetime.dwHighDateTime, filetime.dwLowDateTime);
								}
							}
						  }
						  break;
						case ADSTYPE_NT_SECURITY_DESCRIPTOR:
						  for (x = 0; x< col.dwNumValues; x++)
						  {
							  wprintf(L"  Security descriptor.\n");
						  }
						  break;
						default:
				          wprintf(L"Unknown type %d.\n",col.dwADsType);
					}
				  }
			      else
				  {
					//Verbose handles only the two single-valued attributes: cn and ldapdisplayname
					//so this is a special case.
					
					if (0==wcscmp(L"name", pszColumn))
					{
					  szName[0]=L'\0';
					  if( IS_BUFFER_ENOUGH(MAX_PATH, szName, col.pADsValues->CaseIgnoreString) > 0 )
					  {
					       wcscpy_s(szName,MAX_PATH,col.pADsValues->CaseIgnoreString);
					  }
					}
					if (0==wcscmp(L"distinguishedName", pszColumn))
					{
						szDN[0]=L'\0';
						if( IS_BUFFER_ENOUGH(MAX_PATH, szDN, col.pADsValues->CaseIgnoreString) > 0 )
						{
					       wcscpy_s(szDN,MAX_PATH,col.pADsValues->CaseIgnoreString);
						}
					}
				  }
			      pContainerToSearch->FreeColumn( &col );
			    }
				FreeADsMem( pszColumn );
            }
		   if (!bIsVerbose)
			   wprintf(L"%s\n  DN: %s\n\n",szName,szDN);
 		   //Get the next row
		   hr = pContainerToSearch->GetNextRow( hSearch);
		}

	  }
	  // Close the search handle to clean up
      pContainerToSearch->CloseSearchHandle(hSearch);
	} 
	if (SUCCEEDED(hr) && 0==iCount)
		hr = S_FALSE;
	delete [] pszSearchFilter;
	delete [] szName;
	delete [] szDN;
    return hr;
}
Ejemplo n.º 17
0
//This function was added to CGrandDataFile to recursively retrieve a list of *.BID files in
//a directory.  It reads the file header to populate the CList of tFileRecords that is converted to
//a safe array used by ImportManager.  This was flagrantly stolen from Kelly Michel and modified to
//search for and read in *.BID files. hn 6/8/2005
// 5-Jul-2005 SFK Removed dead code for readability
// 11-Jul-2005 SFK	Copied from GRAND Import and modified for binary
void CBinaryDataFile::GetCompleteFileList(short FacilityID, CList<tFileRecord, tFileRecord> *pFileList, 
									   const CString& Directory,  bool IncludeSubdirs)
{
	//USES_CONVERSION;

	CFileFind Finder;
	BOOL bWorking;
	CString  FileName;
	tFileRecord FileRecord;

	CString DirWithFileMask;
	DirWithFileMask.Format("%s\\*.*", Directory);
	bWorking = Finder.FindFile(DirWithFileMask);

	
	//If this is an "archive" directory, then skip it completely, and everything that may be underneath it.
	int StartSubDirName = Directory.ReverseFind('\\');
	if(StartSubDirName != -1)
	{
		CString SubDirName = Directory.Mid(StartSubDirName + 1);
		if(SubDirName.CompareNoCase("Archive")) //If SubDirName is not Archive...
		{
			do
			{
				bWorking = Finder.FindNextFile();
				
				if(!Finder.IsDots())
				{
					if(Finder.IsDirectory() && IncludeSubdirs)
					{
						//Recurse.
						GetCompleteFileList(FacilityID, pFileList, Finder.GetFilePath(), IncludeSubdirs);
					}
					else //if(Finder.IsNormal())
					{
 						FileName = Finder.GetFileName(); 
						CString Ext = FileName.Mid(FileName.GetLength() - 3, 3);
						if(!Ext.CompareNoCase("BNY"))
						{
							FileRecord.File.bstrVal = (Finder.GetFilePath()).AllocSysString();

							//****************************************************************
							//Open the file and get info on the data in the file.  Load that
							//file data into the FileRecord structure.
							//****************************************************************
							CString err;
							//If we are not able to read the *.BNY header, we fail
							CString cs(FileRecord.File.bstrVal);
							if (!ReadHeader (cs,&err))
							//if (!ReadHeader (W2T(FileRecord.File.bstrVal),&err))
							{
								if (mpFile) CloseDataFile();
							}
							else
							//Otherwise, save the file date and station ID read.
							{
								SYSTEMTIME sysTime;
								COleDateTime fileDate = GetFileDate ();
								fileDate.GetAsSystemTime (sysTime);
								SystemTimeToVariantTime (&sysTime,&FileRecord.Date.date);
								FileRecord.StationID.lVal = (long) GetStationID ();
								pFileList->AddTail (FileRecord);
								CloseDataFile ();
							}
						}
					}
				}		
			}
			while(bWorking != 0);
		}
	}

}
HRESULT FindAttributesOrClasses(IDirectorySearch *pSchemaNC, //IDirectorySearch pointer to schema naming context.
		 LPOLESTR szFilter, //Filter for finding specific attributes.
                            //NULL returns all attributeSchema objects.
         LPOLESTR *pszPropertiesToReturn, //Properties to return for attributeSchema objects found
					                    //NULL returns all set properties unless bIsVerbose is FALSE.
		 BOOL bIsAttributeQuery, //TRUE queries for attributes;FALSE for classes
		 BOOL bIsVerbose //TRUE means all properties for the found objects are displayed.
		                 //FALSE means only the ldapDisplayName with cn in parentheses:
						 //example: l (Locality-Name)
							)
{
	if (!pSchemaNC)
		return E_POINTER;
    //Create search filter
	int allocFilter = MAX_PATH*2;
	LPOLESTR pszSearchFilter = new OLECHAR[allocFilter];
	
    if ( !pszSearchFilter )
    {
        delete [] pszSearchFilter;
        return E_OUTOFMEMORY;
    }
        
	LPOLESTR szCategory = NULL;
	if (bIsAttributeQuery)
		szCategory = L"attributeSchema";
	else
		szCategory = L"classSchema";


	wcscpy_s(pszSearchFilter, allocFilter, L"(&(objectCategory=attributeSchema)%s)");
	BOOL bBufferOK=false;
	// Check for buffer overrun...
	if (szFilter)
	{
		if ( IS_BUFFER_ENOUGH(allocFilter,pszSearchFilter, szCategory) > 0 )
		{
	       swprintf_s(pszSearchFilter, allocFilter, L"(&(objectCategory=%s)%s)",szCategory,szFilter);
		   bBufferOK=true;
		}
	}
	else
	{
		if ( IS_BUFFER_ENOUGH(allocFilter,pszSearchFilter, szCategory) > 0 )
		{
 	       swprintf_s(pszSearchFilter, allocFilter,L"(objectCategory=%s)",szCategory);
		   bBufferOK=true;
		}
	}

	
	if( !bBufferOK)
	{
            delete [] pszSearchFilter;
			wprintf(L"Filter is too large - aborting");
			return E_FAIL;
	}

    //Attributes are one-level deep in the Schema container so only need to search one level.
	ADS_SEARCHPREF_INFO SearchPrefs;
	SearchPrefs.dwSearchPref = ADS_SEARCHPREF_SEARCH_SCOPE;
	SearchPrefs.vValue.dwType = ADSTYPE_INTEGER;
	SearchPrefs.vValue.Integer = ADS_SCOPE_ONELEVEL;
    DWORD dwNumPrefs = 1;

	// COL for iterations
	LPOLESTR pszColumn = NULL;    
	ADS_SEARCH_COLUMN col;
    HRESULT hr;
    
    // Interface Pointers
    IADs    *pObj = NULL;
    IADs	* pIADs = NULL;

    // Handle used for searching
    ADS_SEARCH_HANDLE hSearch = NULL;
	
	// Set the search preference
    hr = pSchemaNC->SetSearchPreference( &SearchPrefs, dwNumPrefs);
    if (FAILED(hr))
        return hr;

	LPOLESTR pszBool = NULL;
	DWORD dwBool;
	PSID pObjectSID = NULL;
	LPOLESTR szSID = NULL;
	LPGUID pObjectGUID = NULL;
	FILETIME filetime;
	SYSTEMTIME systemtime;
	DATE date;
	VARIANT varDate;
	LARGE_INTEGER liValue;
	LPOLESTR *pszPropertyList = NULL;
	LPOLESTR pszNonVerboseList[] = {L"lDAPDisplayName",L"cn"};

	LPOLESTR szCNValue = new OLECHAR[MAX_PATH];
	LPOLESTR szLDAPDispleyNameValue = new OLECHAR[MAX_PATH];
	LPOLESTR szDSGUID = new WCHAR [39];
	
	if ( !szCNValue || 	!szLDAPDispleyNameValue || !szDSGUID )
	{
        if ( szDSGUID )
            delete [] szDSGUID;
        if ( szCNValue )
            delete [] szCNValue;
        if ( szLDAPDispleyNameValue )
            delete [] szLDAPDispleyNameValue;
        if ( pszSearchFilter )
            delete [] pszSearchFilter;	
        return E_OUTOFMEMORY;
    }

	int iCount = 0;
	DWORD x = 0L;



	if (!bIsVerbose)
	{
		 //Return non-verbose list properties only
         hr = pSchemaNC->ExecuteSearch(pszSearchFilter,
		                          pszNonVerboseList,
								  sizeof(pszNonVerboseList)/sizeof(LPOLESTR),
								  &hSearch
								  );
	}
	else
	{
		if (!pszPropertiesToReturn)
		{
			//Return all properties.
			hr = pSchemaNC->ExecuteSearch(pszSearchFilter,
		                          NULL,
								  0L,
								  &hSearch
								  );
		}
		else
		{
			//specified subset.
		    pszPropertyList = pszPropertiesToReturn;
		   //Return specified properties
		   hr = pSchemaNC->ExecuteSearch(pszSearchFilter,
		                          pszPropertyList,
								  sizeof(pszPropertyList)/sizeof(LPOLESTR),
								  &hSearch
								  );
		}
	}
 	if ( SUCCEEDED(hr) )
	{    
    // Call IDirectorySearch::GetNextRow() to retrieve the next row 
    //of data
	  hr = pSchemaNC->GetFirstRow( hSearch);
	  if (SUCCEEDED(hr))
	  {
        while( hr != S_ADS_NOMORE_ROWS )
		{
			//Keep track of count.
			iCount++;
			if (bIsVerbose)
			  wprintf(L"----------------------------------\n");
            // loop through the array of passed column names,
            // print the data for each column

			while( pSchemaNC->GetNextColumnName( hSearch, &pszColumn ) != S_ADS_NOMORE_COLUMNS )
            {
                hr = pSchemaNC->GetColumn( hSearch, pszColumn, &col );
			    if ( SUCCEEDED(hr) )
			    {
		            // Print the data for the column and free the column
				  if(bIsVerbose)
				  {
			        // Get the data for this column
				    wprintf(L"%s\n",col.pszAttrName);
					switch (col.dwADsType)
					{
						case ADSTYPE_DN_STRING:
                          for (x = 0; x< col.dwNumValues; x++)
						  {
							  wprintf(L"  %s\r\n",col.pADsValues[x].DNString);
						  }
						  break;
						case ADSTYPE_CASE_EXACT_STRING:	    
						case ADSTYPE_CASE_IGNORE_STRING:	    
						case ADSTYPE_PRINTABLE_STRING:	    
						case ADSTYPE_NUMERIC_STRING:	        
						case ADSTYPE_TYPEDNAME:	            
						case ADSTYPE_FAXNUMBER:	            
						case ADSTYPE_PATH:	                
						case ADSTYPE_OBJECT_CLASS:
						  for (x = 0; x< col.dwNumValues; x++)
						  {
							  wprintf(L"  %s\r\n",col.pADsValues[x].CaseIgnoreString);
						  }
						  break;
						case ADSTYPE_BOOLEAN:
						  for (x = 0; x< col.dwNumValues; x++)
						  {
							  dwBool = col.pADsValues[x].Boolean;
							  pszBool = dwBool ? L"TRUE" : L"FALSE";
							  wprintf(L"  %s\r\n",pszBool);
						  }
						  break;
						case ADSTYPE_INTEGER:
					      for (x = 0; x< col.dwNumValues; x++)
						  {
							  wprintf(L"  %d\r\n",col.pADsValues[x].Integer);
						  }
						  break;
						case ADSTYPE_OCTET_STRING:
						    if ( _wcsicmp(col.pszAttrName,L"objectSID") == 0 )
							{
						      for (x = 0; x< col.dwNumValues; x++)
							  {
								  pObjectSID = (PSID)(col.pADsValues[x].OctetString.lpValue);
								  //Convert SID to string.
								  ConvertSidToStringSid(pObjectSID, &szSID);
								  wprintf(L"  %s\r\n",szSID);
								  LocalFree(szSID);
							  }
							}
						    else if ( (_wcsicmp(col.pszAttrName,L"objectGUID") == 0)
								|| (_wcsicmp(col.pszAttrName,L"schemaIDGUID") == 0) 
								|| (_wcsicmp(col.pszAttrName,L"attributeSecurityGUID") == 0) )
							{
						      for (x = 0; x< col.dwNumValues; x++)
							  {
								//Cast to LPGUID
								pObjectGUID = (LPGUID)(col.pADsValues[x].OctetString.lpValue);
								//Convert GUID to string.
								::StringFromGUID2(*pObjectGUID, szDSGUID, 39); 
								//Print the GUID
								wprintf(L"  %s\r\n",szDSGUID);
							  }
							}
						    else if ( _wcsicmp(col.pszAttrName,L"oMObjectClass") == 0 )
							{
							  //TODO: 
							  wprintf(L"  TODO:No conversion for this.");
							}
							else
							  wprintf(L"  Value of type Octet String. No Conversion.");
						    break;
						case ADSTYPE_UTC_TIME:
						  for (x = 0; x< col.dwNumValues; x++)
						  {
							systemtime = col.pADsValues[x].UTCTime;
							if (SystemTimeToVariantTime(&systemtime,
														&date) != 0) 
							{
								//Pack in variant.vt
								varDate.vt = VT_DATE;
								varDate.date = date;
								VariantChangeType(&varDate,&varDate,VARIANT_NOVALUEPROP,VT_BSTR);
							    wprintf(L"  %s\r\n",varDate.bstrVal);
								VariantClear(&varDate);
							}
							else
								wprintf(L"  Could not convert UTC-Time.\n");
						  }
						  break;
						case ADSTYPE_LARGE_INTEGER:
						  for (x = 0; x< col.dwNumValues; x++)
						  {
						    liValue = col.pADsValues[x].LargeInteger;
							filetime.dwLowDateTime = liValue.LowPart;
							filetime.dwHighDateTime = liValue.HighPart;
							if((filetime.dwHighDateTime==0) && (filetime.dwLowDateTime==0))
							{
								wprintf(L"  No value set.\n");
							}
							else
							{
								//Check for properties of type LargeInteger that represent time
								//if TRUE, then convert to variant time.
								if ((0==wcscmp(L"accountExpires", col.pszAttrName))|
									(0==wcscmp(L"badPasswordTime", col.pszAttrName))||
									(0==wcscmp(L"lastLogon", col.pszAttrName))||
									(0==wcscmp(L"lastLogoff", col.pszAttrName))||
									(0==wcscmp(L"lockoutTime", col.pszAttrName))||
									(0==wcscmp(L"pwdLastSet", col.pszAttrName))
								   )
								{
									//Handle special case for Never Expires where low part is -1
									if (filetime.dwLowDateTime==-1)
									{
										wprintf(L"  Never Expires.\n");
									}
									else
									{
										if (FileTimeToLocalFileTime(&filetime, &filetime) != 0) 
										{
											if (FileTimeToSystemTime(&filetime,
																 &systemtime) != 0)
											{
												if (SystemTimeToVariantTime(&systemtime,
																			&date) != 0) 
												{
													//Pack in variant.vt
													varDate.vt = VT_DATE;
													varDate.date = date;
													VariantChangeType(&varDate,&varDate,VARIANT_NOVALUEPROP,VT_BSTR);
													wprintf(L"  %s\r\n",varDate.bstrVal);
													VariantClear(&varDate);
												}
												else
												{
													wprintf(L"  FileTimeToVariantTime failed\n");
												}
											}
											else
											{
												wprintf(L"  FileTimeToSystemTime failed\n");
											}

										}
										else
										{
											wprintf(L"  FileTimeToLocalFileTime failed\n");
										}
									}
								}
								else
								{
									//Print the LargeInteger.
									wprintf(L"  high: %d low: %d\r\n",filetime.dwHighDateTime, filetime.dwLowDateTime);
								}
							}
						  }
						  break;
						case ADSTYPE_NT_SECURITY_DESCRIPTOR:
						  for (x = 0; x< col.dwNumValues; x++)
						  {
							  wprintf(L"  Security descriptor.\n");
						  }
						  break;
						default:
				          wprintf(L"Unknown type %d.\n",col.dwADsType);
					}
				  }
			      else
				  {
					//Verbose handles only the two single-valued attributes: cn and ldapdisplayname
					//so this is a special case.
					if (0==wcscmp(L"cn", pszColumn))
					{
					  wcscpy_s(szCNValue,MAX_PATH,col.pADsValues->CaseIgnoreString);
					}
					if (0==wcscmp(L"lDAPDisplayName", pszColumn))
					{
					  wcscpy_s(szLDAPDispleyNameValue,MAX_PATH,col.pADsValues->CaseIgnoreString);
					}
				  }
			      pSchemaNC->FreeColumn( &col );
			    }
				FreeADsMem( pszColumn );
            }
		   if (!bIsVerbose)
			   wprintf(L"%s (%s)\n",szLDAPDispleyNameValue,szCNValue);
 		   //Get the next row
		   hr = pSchemaNC->GetNextRow( hSearch);
		}

	  }
	  // Close the search handle to clean up
      pSchemaNC->CloseSearchHandle(hSearch);
	} 
	if (SUCCEEDED(hr) && 0==iCount)
		hr = S_FALSE;

    delete [] szDSGUID;
    delete [] szCNValue;
    delete [] szLDAPDispleyNameValue;
    delete [] pszSearchFilter;
        
    return hr;
}
Ejemplo n.º 19
0
PHPAPI void php_pval_to_variant_ex(pval *pval_arg, VARIANT *var_arg, pval *pval_type, int codepage)
{
      OLECHAR *unicode_str;

      var_arg->vt = (short) pval_type->value.lval;

      switch(var_arg->vt)
      {
         case VT_UI1:
            convert_to_long_ex(&pval_arg);
            var_arg->bVal = (unsigned char)pval_arg->value.lval;
            break;

         case VT_I2:
            convert_to_long_ex(&pval_arg);
            var_arg->iVal = (short)pval_arg->value.lval;
            break;

         case VT_I4:
            convert_to_long_ex(&pval_arg);
            var_arg->lVal = pval_arg->value.lval;
            break;

         case VT_R4:
            convert_to_double_ex(&pval_arg);
            var_arg->fltVal = (float)pval_arg->value.dval;
            break;

         case VT_R8:
            convert_to_double_ex(&pval_arg);
            var_arg->dblVal = pval_arg->value.dval;
            break;

         case VT_BOOL:
            convert_to_boolean_ex(&pval_arg);
            var_arg->boolVal = (short)pval_arg->value.lval;
            break;

         case VT_ERROR:
            convert_to_long_ex(&pval_arg);
            var_arg->scode = pval_arg->value.lval;
            break;

         case VT_CY:
            convert_to_double_ex(&pval_arg);
            VarCyFromR8(pval_arg->value.dval, &(var_arg->cyVal));
            break;

         case VT_DATE:
         {
            SYSTEMTIME wintime;
            struct tm *phptime;

            phptime = gmtime(&(pval_arg->value.lval));

            wintime.wYear = phptime->tm_year + 1900;
            wintime.wMonth = phptime->tm_mon + 1;
            wintime.wDay = phptime->tm_mday;
            wintime.wHour = phptime->tm_hour;
            wintime.wMinute = phptime->tm_min;
            wintime.wSecond = phptime->tm_sec;

            SystemTimeToVariantTime(&wintime, &(var_arg->date));
         }

         case VT_BSTR:
            convert_to_string_ex(&pval_arg);
            unicode_str = php_char_to_OLECHAR(pval_arg->value.str.val, pval_arg->value.str.len, codepage);
            var_arg->bstrVal = SysAllocString(unicode_str);
            efree(unicode_str);
            break;

         case VT_DECIMAL:
            convert_to_string_ex(&pval_arg);
            unicode_str = php_char_to_OLECHAR(pval_arg->value.str.val, pval_arg->value.str.len, codepage);
            VarDecFromStr(unicode_str, LOCALE_SYSTEM_DEFAULT, 0, &(var_arg->decVal));
            break;

         case VT_DECIMAL|VT_BYREF:
            convert_to_string_ex(&pval_arg);
            unicode_str = php_char_to_OLECHAR(pval_arg->value.str.val, pval_arg->value.str.len, codepage);
            VarDecFromStr(unicode_str, LOCALE_SYSTEM_DEFAULT, 0, var_arg->pdecVal);
            break;

         case VT_UNKNOWN:
            php_pval_to_variant(pval_arg, var_arg, codepage);
            if(var_arg->vt != VT_DISPATCH)
               var_arg->vt = VT_EMPTY;
            else
            {
               HRESULT hr;

               hr = var_arg->pdispVal->lpVtbl->QueryInterface(var_arg->pdispVal, &IID_IUnknown, &(var_arg->punkVal));

               if (FAILED(hr))
               {
                  php_error(E_WARNING,"can't query IUnknown");
                  var_arg->vt = VT_EMPTY;
               }
               else
                  var_arg->vt = VT_UNKNOWN;
            }
            break;

         case VT_DISPATCH:
            php_pval_to_variant(pval_arg, var_arg, codepage);
            if(var_arg->vt != VT_DISPATCH)
               var_arg->vt = VT_EMPTY;
            break;

         case VT_UI1|VT_BYREF:
            convert_to_long(pval_arg);
            var_arg->pbVal = (unsigned char FAR*) &(pval_arg->value.lval);
            break;

         case VT_I2|VT_BYREF:
            convert_to_long(pval_arg);
            var_arg->piVal = (short FAR*) &(pval_arg->value.lval);
            break;

         case VT_I4|VT_BYREF:
            convert_to_long(pval_arg);
            var_arg->plVal = (long FAR*) &(pval_arg->value.lval);
            break;

         case VT_R4|VT_BYREF:
            convert_to_double(pval_arg);
            var_arg->pfltVal = (float FAR*) &(pval_arg->value.lval);
            break;

         case VT_R8|VT_BYREF:
            convert_to_double(pval_arg);
            var_arg->pdblVal = (double FAR*) &(pval_arg->value.lval);
            break;

         case VT_BOOL|VT_BYREF:
            convert_to_boolean(pval_arg);
            var_arg->pboolVal = (short FAR*) &(pval_arg->value.lval);
            break;

         case VT_ERROR|VT_BYREF:
            convert_to_long(pval_arg);
            var_arg->pscode = (long FAR*) &(pval_arg->value.lval);
            break;

         case VT_CY|VT_BYREF:
            convert_to_double_ex(&pval_arg);
            VarCyFromR8(pval_arg->value.dval, var_arg->pcyVal);
            break;

         case VT_DATE|VT_BYREF:
         {
            SYSTEMTIME wintime;
            struct tm *phptime;

            phptime = gmtime(&(pval_arg->value.lval));

            wintime.wYear   = phptime->tm_year + 1900;
            wintime.wMonth  = phptime->tm_mon + 1;
            wintime.wDay    = phptime->tm_mday;
            wintime.wHour   = phptime->tm_hour;
            wintime.wMinute = phptime->tm_min;
            wintime.wSecond = phptime->tm_sec;

            SystemTimeToVariantTime(&wintime, var_arg->pdate);
         }

         case VT_BSTR|VT_BYREF:
            convert_to_string(pval_arg);
            var_arg->pbstrVal = (BSTR FAR*) emalloc(sizeof(BSTR FAR*));
            unicode_str = php_char_to_OLECHAR(pval_arg->value.str.val, pval_arg->value.str.len, codepage);
            *(var_arg->pbstrVal) = SysAllocString(unicode_str);
            efree(unicode_str);
            break;

         case VT_UNKNOWN|VT_BYREF:
            php_pval_to_variant(pval_arg, var_arg, codepage);
            if(var_arg->vt != VT_DISPATCH)
               var_arg->vt = VT_EMPTY;
            else
            {
               HRESULT hr;

               hr = var_arg->pdispVal->lpVtbl->QueryInterface(var_arg->pdispVal, &IID_IUnknown, &(var_arg->punkVal));

               if (FAILED(hr))
               {
                  php_error(E_WARNING,"can't query IUnknown");
                  var_arg->vt = VT_EMPTY;
               }
               else
                  var_arg->vt = VT_UNKNOWN|VT_BYREF;
            }
            break;

         case VT_DISPATCH|VT_BYREF:
            php_pval_to_variant(pval_arg, var_arg, codepage);
            if(var_arg->vt != VT_DISPATCH)
               var_arg->vt = VT_EMPTY;
            else
               var_arg->vt |= VT_BYREF;
            break;

         case VT_VARIANT|VT_BYREF:
            php_pval_to_variant(pval_arg, var_arg, codepage);
            if(var_arg->vt != (VT_VARIANT | VT_BYREF))
               var_arg->vt = VT_EMPTY;
            break;

         case VT_I1:
            convert_to_long_ex(&pval_arg);
            var_arg->cVal = (char)pval_arg->value.lval;
            break;

         case VT_UI2:
            convert_to_long_ex(&pval_arg);
            var_arg->uiVal = (unsigned short)pval_arg->value.lval;
            break;

         case VT_UI4:
            convert_to_long_ex(&pval_arg);
            var_arg->ulVal = (unsigned long)pval_arg->value.lval;
            break;

         case VT_INT:
            convert_to_long_ex(&pval_arg);
            var_arg->intVal = (int)pval_arg->value.lval;
            break;

         case VT_UINT:
            convert_to_long_ex(&pval_arg);
            var_arg->uintVal = (unsigned int)pval_arg->value.lval;
            break;

         case VT_I1|VT_BYREF:
            convert_to_long(pval_arg);
            var_arg->pcVal = (char FAR*) &pval_arg->value.lval;
            break;

         case VT_UI2|VT_BYREF:
            convert_to_long(pval_arg);
            var_arg->puiVal = (unsigned short FAR*) &pval_arg->value.lval;
            break;

         case VT_UI4|VT_BYREF:
            convert_to_long(pval_arg);
            var_arg->pulVal = (unsigned long FAR*) &pval_arg->value.lval;
            break;

         case VT_INT|VT_BYREF:
            convert_to_long(pval_arg);
            var_arg->pintVal = (int FAR*) &pval_arg->value.lval;
            break;

         case VT_UINT|VT_BYREF:
            convert_to_long(pval_arg);
            var_arg->puintVal = (unsigned int FAR*) &pval_arg->value.lval;
            break;

         default:
            php_error(E_WARNING, "Type not supportet or not yet implemented.");
      }
}
Ejemplo n.º 20
0
static HRESULT WINAPI convert_DataConvert(IDataConvert* iface,
                                          DBTYPE src_type, DBTYPE dst_type,
                                          DBLENGTH src_len, DBLENGTH *dst_len,
                                          void *src, void *dst,
                                          DBLENGTH dst_max_len,
                                          DBSTATUS src_status, DBSTATUS *dst_status,
                                          BYTE precision, BYTE scale,
                                          DBDATACONVERT flags)
{
    convert *This = impl_from_IDataConvert(iface);
    HRESULT hr;

    TRACE("(%p)->(%d, %d, %ld, %p, %p, %p, %ld, %d, %p, %d, %d, %x)\n", This,
          src_type, dst_type, src_len, dst_len, src, dst, dst_max_len,
          src_status, dst_status, precision, scale, flags);

    *dst_status = DBSTATUS_E_BADACCESSOR;

    if(IDataConvert_CanConvert(iface, src_type, dst_type) != S_OK)
    {
        return DB_E_UNSUPPORTEDCONVERSION;
    }

    if(src_type == DBTYPE_STR)
    {
        BSTR b;
        DWORD len;

        if(flags & DBDATACONVERT_LENGTHFROMNTS)
            len = MultiByteToWideChar(CP_ACP, 0, src, -1, NULL, 0) - 1;
        else
            len = MultiByteToWideChar(CP_ACP, 0, src, src_len, NULL, 0);
        b = SysAllocStringLen(NULL, len);
        if(!b) return E_OUTOFMEMORY;
        if(flags & DBDATACONVERT_LENGTHFROMNTS)
            MultiByteToWideChar(CP_ACP, 0, src, -1, b, len + 1);
        else
            MultiByteToWideChar(CP_ACP, 0, src, src_len, b, len);

        hr = IDataConvert_DataConvert(iface, DBTYPE_BSTR, dst_type, 0, dst_len,
                                      &b, dst, dst_max_len, src_status, dst_status,
                                      precision, scale, flags);

        SysFreeString(b);
        return hr;
    }

    if(src_type == DBTYPE_WSTR)
    {
        BSTR b;

        if(flags & DBDATACONVERT_LENGTHFROMNTS)
            b = SysAllocString(src);
        else
            b = SysAllocStringLen(src, src_len / 2);
        if(!b) return E_OUTOFMEMORY;
        hr = IDataConvert_DataConvert(iface, DBTYPE_BSTR, dst_type, 0, dst_len,
                                      &b, dst, dst_max_len, src_status, dst_status,
                                      precision, scale, flags);
        SysFreeString(b);
        return hr;
    }

    switch(dst_type)
    {
    case DBTYPE_I2:
    {
        signed short *d = dst;
        VARIANT tmp;
        switch(src_type)
        {
        case DBTYPE_EMPTY:       *d = 0; hr = S_OK;                              break;
        case DBTYPE_I2:          *d = *(signed short*)src; hr = S_OK;            break;
        case DBTYPE_I4:          hr = VarI2FromI4(*(signed int*)src, d);         break;
        case DBTYPE_R4:          hr = VarI2FromR4(*(FLOAT*)src, d);              break;
        case DBTYPE_R8:          hr = VarI2FromR8(*(double*)src, d);             break;
        case DBTYPE_CY:          hr = VarI2FromCy(*(CY*)src, d);                 break;
        case DBTYPE_DATE:        hr = VarI2FromDate(*(DATE*)src, d);             break;
        case DBTYPE_BSTR:        hr = VarI2FromStr(*(WCHAR**)src, LOCALE_USER_DEFAULT, 0, d); break;
        case DBTYPE_BOOL:        hr = VarI2FromBool(*(VARIANT_BOOL*)src, d);     break;
        case DBTYPE_DECIMAL:     hr = VarI2FromDec((DECIMAL*)src, d);            break;
        case DBTYPE_I1:          hr = VarI2FromI1(*(signed char*)src, d);        break;
        case DBTYPE_UI1:         hr = VarI2FromUI1(*(BYTE*)src, d);              break;
        case DBTYPE_UI2:         hr = VarI2FromUI2(*(WORD*)src, d);              break;
        case DBTYPE_UI4:         hr = VarI2FromUI4(*(DWORD*)src, d);             break;
        case DBTYPE_I8:          hr = VarI2FromI8(*(LONGLONG*)src, d);           break;
        case DBTYPE_UI8:         hr = VarI2FromUI8(*(ULONGLONG*)src, d);         break;
        case DBTYPE_VARIANT:
            VariantInit(&tmp);
            if ((hr = VariantChangeType(&tmp, (VARIANT*)src, 0, VT_I2)) == S_OK)
                *d = V_I2(&tmp);
            break;
        default: FIXME("Unimplemented conversion %04x -> I2\n", src_type); return E_NOTIMPL;
        }
        break;
    }

    case DBTYPE_I4:
    {
        signed int *d = dst;
        VARIANT tmp;
        switch(src_type)
        {
        case DBTYPE_EMPTY:       *d = 0; hr = S_OK;                              break;
        case DBTYPE_I2:          hr = VarI4FromI2(*(signed short*)src, d);       break;
        case DBTYPE_I4:          *d = *(signed int*)src; hr = S_OK;              break;
        case DBTYPE_R4:          hr = VarI4FromR4(*(FLOAT*)src, d);              break;
        case DBTYPE_R8:          hr = VarI4FromR8(*(double*)src, d);             break;
        case DBTYPE_CY:          hr = VarI4FromCy(*(CY*)src, d);                 break;
        case DBTYPE_DATE:        hr = VarI4FromDate(*(DATE*)src, d);             break;
        case DBTYPE_BSTR:        hr = VarI4FromStr(*(WCHAR**)src, LOCALE_USER_DEFAULT, 0, d); break;
        case DBTYPE_BOOL:        hr = VarI4FromBool(*(VARIANT_BOOL*)src, d);     break;
        case DBTYPE_DECIMAL:     hr = VarI4FromDec((DECIMAL*)src, d);            break;
        case DBTYPE_I1:          hr = VarI4FromI1(*(signed char*)src, d);        break;
        case DBTYPE_UI1:         hr = VarI4FromUI1(*(BYTE*)src, d);              break;
        case DBTYPE_UI2:         hr = VarI4FromUI2(*(WORD*)src, d);              break;
        case DBTYPE_UI4:         hr = VarI4FromUI4(*(DWORD*)src, d);             break;
        case DBTYPE_I8:          hr = VarI4FromI8(*(LONGLONG*)src, d);           break;
        case DBTYPE_UI8:         hr = VarI4FromUI8(*(ULONGLONG*)src, d);         break;
        case DBTYPE_VARIANT:
            VariantInit(&tmp);
            if ((hr = VariantChangeType(&tmp, (VARIANT*)src, 0, VT_I4)) == S_OK)
                *d = V_I4(&tmp);
            break;
        default: FIXME("Unimplemented conversion %04x -> I4\n", src_type); return E_NOTIMPL;
        }
        break;
    }

    case DBTYPE_R4:
    {
        FLOAT *d = dst;
        switch(src_type)
        {
        case DBTYPE_EMPTY:       *d = 0; hr = S_OK;                              break;
        case DBTYPE_I2:          hr = VarR4FromI2(*(signed short*)src, d);       break;
        case DBTYPE_I4:          hr = VarR4FromI4(*(signed int*)src, d);         break;
        case DBTYPE_R4:          *d = *(FLOAT*)src; hr = S_OK;                   break;
        case DBTYPE_R8:          hr = VarR4FromR8(*(double*)src, d);             break;
        case DBTYPE_CY:          hr = VarR4FromCy(*(CY*)src, d);                 break;
        case DBTYPE_DATE:        hr = VarR4FromDate(*(DATE*)src, d);             break;
        case DBTYPE_BSTR:        hr = VarR4FromStr(*(WCHAR**)src, LOCALE_USER_DEFAULT, 0, d); break;
        case DBTYPE_BOOL:        hr = VarR4FromBool(*(VARIANT_BOOL*)src, d);     break;
        case DBTYPE_DECIMAL:     hr = VarR4FromDec((DECIMAL*)src, d);            break;
        case DBTYPE_I1:          hr = VarR4FromI1(*(signed char*)src, d);        break;
        case DBTYPE_UI1:         hr = VarR4FromUI1(*(BYTE*)src, d);              break;
        case DBTYPE_UI2:         hr = VarR4FromUI2(*(WORD*)src, d);              break;
        case DBTYPE_UI4:         hr = VarR4FromUI4(*(DWORD*)src, d);             break;
        case DBTYPE_I8:          hr = VarR4FromI8(*(LONGLONG*)src, d);           break;
        case DBTYPE_UI8:         hr = VarR4FromUI8(*(ULONGLONG*)src, d);         break;
        default: FIXME("Unimplemented conversion %04x -> R4\n", src_type); return E_NOTIMPL;
        }
        break;
    }
    case DBTYPE_R8:
    {
        DOUBLE *d=dst;
        switch (src_type)
        {
        case DBTYPE_EMPTY:      *d = 0; hr = S_OK;                               break;
        case DBTYPE_I1:          hr = VarR8FromI1(*(signed char*)src, d);        break;
        case DBTYPE_I2:          hr = VarR8FromI2(*(signed short*)src, d);       break;
        case DBTYPE_I4:          hr = VarR8FromI4(*(signed int*)src, d);         break;
        case DBTYPE_I8:          hr = VarR8FromI8(*(LONGLONG*)src, d);           break;
        case DBTYPE_UI1:         hr = VarR8FromUI1(*(BYTE*)src, d);              break;
        case DBTYPE_UI2:         hr = VarR8FromUI2(*(WORD*)src, d);              break;
        case DBTYPE_UI4:         hr = VarR8FromUI4(*(DWORD*)src, d);             break;
        case DBTYPE_UI8:         hr = VarR8FromUI8(*(ULONGLONG*)src, d);         break;
        case DBTYPE_R4:          hr = VarR8FromR4(*(FLOAT*)src, d);              break;
        case DBTYPE_R8:          *d = *(DOUBLE*)src; hr = S_OK;                  break;
        case DBTYPE_CY:          hr = VarR8FromCy(*(CY*)src, d);                 break;
        case DBTYPE_DATE:        hr = VarR8FromDate(*(DATE*)src, d);             break;
        case DBTYPE_BSTR:        hr = VarR8FromStr(*(WCHAR**)src, LOCALE_USER_DEFAULT, 0, d); break;
        case DBTYPE_BOOL:        hr = VarR8FromBool(*(VARIANT_BOOL*)src, d);     break;
        case DBTYPE_DECIMAL:     hr = VarR8FromDec((DECIMAL*)src, d);            break;
        default: FIXME("Unimplemented conversion %04x -> R8\n", src_type); return E_NOTIMPL;
        }
        break;
    }
    case DBTYPE_BOOL:
    {
        VARIANT_BOOL *d=dst;
        switch (src_type)
        {
        case DBTYPE_EMPTY:      *d = 0; hr = S_OK;                               break;
        case DBTYPE_I1:          hr = VarBoolFromI1(*(signed char*)src, d);      break;
        case DBTYPE_I2:          hr = VarBoolFromI2(*(signed short*)src, d);     break;
        case DBTYPE_I4:          hr = VarBoolFromI4(*(signed int*)src, d);       break;
        case DBTYPE_I8:          hr = VarBoolFromI8(*(LONGLONG*)src, d);         break;
        case DBTYPE_UI1:         hr = VarBoolFromUI1(*(BYTE*)src, d);            break;
        case DBTYPE_UI2:         hr = VarBoolFromUI2(*(WORD*)src, d);            break;
        case DBTYPE_UI4:         hr = VarBoolFromUI4(*(DWORD*)src, d);           break;
        case DBTYPE_UI8:         hr = VarBoolFromUI8(*(ULONGLONG*)src, d);       break;
        case DBTYPE_R4:          hr = VarBoolFromR4(*(FLOAT*)src, d);            break;
        case DBTYPE_R8:          hr = VarBoolFromR8(*(DOUBLE*)src, d);           break;
        case DBTYPE_CY:          hr = VarBoolFromCy(*(CY*)src, d);               break;
        case DBTYPE_DATE:        hr = VarBoolFromDate(*(DATE*)src, d);           break;
        case DBTYPE_BSTR:        hr = VarBoolFromStr(*(WCHAR**)src, LOCALE_USER_DEFAULT, 0, d); break;
        case DBTYPE_BOOL:        *d = *(VARIANT_BOOL*)src; hr = S_OK;            break;
        case DBTYPE_DECIMAL:     hr = VarBoolFromDec((DECIMAL*)src, d);          break;
        default: FIXME("Unimplemented conversion %04x -> BOOL\n", src_type); return E_NOTIMPL;
        }
        break;
    }
    case DBTYPE_DATE:
    {
        DATE *d=dst;
        switch (src_type)
        {
        case DBTYPE_EMPTY:      *d = 0; hr = S_OK;                           	 break;
        case DBTYPE_I1:          hr = VarDateFromI1(*(signed char*)src, d);      break;
        case DBTYPE_I2:          hr = VarDateFromI2(*(signed short*)src, d);     break;
        case DBTYPE_I4:          hr = VarDateFromI4(*(signed int*)src, d);       break;
        case DBTYPE_I8:          hr = VarDateFromI8(*(LONGLONG*)src, d);         break;
        case DBTYPE_UI1:         hr = VarDateFromUI1(*(BYTE*)src, d);            break;
        case DBTYPE_UI2:         hr = VarDateFromUI2(*(WORD*)src, d);            break;
        case DBTYPE_UI4:         hr = VarDateFromUI4(*(DWORD*)src, d);           break;
        case DBTYPE_UI8:         hr = VarDateFromUI8(*(ULONGLONG*)src, d);       break;
        case DBTYPE_R4:          hr = VarDateFromR4(*(FLOAT*)src, d);            break;
        case DBTYPE_R8:          hr = VarDateFromR8(*(DOUBLE*)src, d);           break;
        case DBTYPE_CY:          hr = VarDateFromCy(*(CY*)src, d);               break;
        case DBTYPE_DATE:       *d = *(DATE*)src;      hr = S_OK;                break;
        case DBTYPE_BSTR:        hr = VarDateFromStr(*(WCHAR**)src, LOCALE_USER_DEFAULT, 0, d); break;
        case DBTYPE_BOOL:        hr = VarDateFromBool(*(VARIANT_BOOL*)src, d);   break;
        case DBTYPE_DECIMAL:     hr = VarDateFromDec((DECIMAL*)src, d);          break;
        case DBTYPE_DBTIMESTAMP:
        {
            SYSTEMTIME st;
            DBTIMESTAMP *ts=(DBTIMESTAMP*)src;

            st.wYear = ts->year;
            st.wMonth = ts->month;
            st.wDay = ts->day;
            st.wHour = ts->hour;
            st.wMinute = ts->minute;
            st.wSecond = ts->second;
            st.wMilliseconds = ts->fraction/1000000;
            hr = (SystemTimeToVariantTime(&st, d) ? S_OK : E_FAIL);
            break;
        }
        default: FIXME("Unimplemented conversion %04x -> DATE\n", src_type); return E_NOTIMPL;
        }
        break;
    }
    case DBTYPE_DBTIMESTAMP:
    {
        DBTIMESTAMP *d=dst;
        switch (src_type)
        {
	case DBTYPE_EMPTY:       memset(d, 0, sizeof(DBTIMESTAMP));    hr = S_OK; break;
	case DBTYPE_DBTIMESTAMP: memcpy(d, src, sizeof(DBTIMESTAMP));  hr = S_OK; break;
        case DBTYPE_DATE:
        {
            SYSTEMTIME st;
            hr = (VariantTimeToSystemTime(*(double*)src, &st) ? S_OK : E_FAIL);
            d->year = st.wYear;
            d->month = st.wMonth;
            d->day = st.wDay;
            d->hour = st.wHour;
            d->minute = st.wMinute;
            d->second = st.wSecond;
            d->fraction = st.wMilliseconds * 1000000;
            break;
        }
        default: FIXME("Unimplemented conversion %04x -> DBTIMESTAMP\n", src_type); return E_NOTIMPL;
        }
        break;
    }

    case DBTYPE_CY:
    {
        CY *d = dst;
        switch(src_type)
        {
        case DBTYPE_EMPTY:       d->int64 = 0; hr = S_OK;                              break;
        case DBTYPE_I2:          hr = VarCyFromI2(*(signed short*)src, d);       break;
        case DBTYPE_I4:          hr = VarCyFromI4(*(signed int*)src, d);         break;
        case DBTYPE_R4:          hr = VarCyFromR4(*(FLOAT*)src, d);              break;
        case DBTYPE_R8:          hr = VarCyFromR8(*(double*)src, d);             break;
        case DBTYPE_CY:          *d = *(CY*)src; hr = S_OK;                      break;
        case DBTYPE_DATE:        hr = VarCyFromDate(*(DATE*)src, d);             break;
        case DBTYPE_BSTR:        hr = VarCyFromStr(*(WCHAR**)src, LOCALE_USER_DEFAULT, 0, d); break;
        case DBTYPE_BOOL:        hr = VarCyFromBool(*(VARIANT_BOOL*)src, d);     break;
        case DBTYPE_DECIMAL:     hr = VarCyFromDec((DECIMAL*)src, d);            break;
        case DBTYPE_I1:          hr = VarCyFromI1(*(signed char*)src, d);        break;
        case DBTYPE_UI1:         hr = VarCyFromUI1(*(BYTE*)src, d);              break;
        case DBTYPE_UI2:         hr = VarCyFromUI2(*(WORD*)src, d);              break;
        case DBTYPE_UI4:         hr = VarCyFromUI4(*(DWORD*)src, d);             break;
        case DBTYPE_I8:          hr = VarCyFromI8(*(LONGLONG*)src, d);           break;
        case DBTYPE_UI8:         hr = VarCyFromUI8(*(ULONGLONG*)src, d);         break;
        default: FIXME("Unimplemented conversion %04x -> CY\n", src_type); return E_NOTIMPL;
        }
        break;
    }

    case DBTYPE_BSTR:
    {
        BSTR *d = dst;
        switch(src_type)
        {
        case DBTYPE_EMPTY:       *d = SysAllocStringLen(NULL, 0); hr = *d ? S_OK : E_OUTOFMEMORY;      break;
        case DBTYPE_I2:          hr = VarBstrFromI2(*(signed short*)src, LOCALE_USER_DEFAULT, 0, d);   break;
        case DBTYPE_I4:          hr = VarBstrFromI4(*(signed int*)src, LOCALE_USER_DEFAULT, 0, d);     break;
        case DBTYPE_R4:          hr = VarBstrFromR4(*(FLOAT*)src, LOCALE_USER_DEFAULT, 0, d);          break;
        case DBTYPE_R8:          hr = VarBstrFromR8(*(double*)src, LOCALE_USER_DEFAULT, 0, d);         break;
        case DBTYPE_CY:          hr = VarBstrFromCy(*(CY*)src, LOCALE_USER_DEFAULT, 0, d);             break;
        case DBTYPE_DATE:        hr = VarBstrFromDate(*(DATE*)src, LOCALE_USER_DEFAULT, 0, d);         break;
        case DBTYPE_BSTR:        *d = SysAllocStringLen(*(BSTR*)src, SysStringLen(*(BSTR*)src)); hr = *d ? S_OK : E_OUTOFMEMORY;     break;
        case DBTYPE_BOOL:        hr = VarBstrFromBool(*(VARIANT_BOOL*)src, LOCALE_USER_DEFAULT, 0, d); break;
        case DBTYPE_DECIMAL:     hr = VarBstrFromDec((DECIMAL*)src, LOCALE_USER_DEFAULT, 0, d);        break;
        case DBTYPE_I1:          hr = VarBstrFromI1(*(signed char*)src, LOCALE_USER_DEFAULT, 0, d);    break;
        case DBTYPE_UI1:         hr = VarBstrFromUI1(*(BYTE*)src, LOCALE_USER_DEFAULT, 0, d);          break;
        case DBTYPE_UI2:         hr = VarBstrFromUI2(*(WORD*)src, LOCALE_USER_DEFAULT, 0, d);          break;
        case DBTYPE_UI4:         hr = VarBstrFromUI4(*(DWORD*)src, LOCALE_USER_DEFAULT, 0, d);         break;
        case DBTYPE_I8:          hr = VarBstrFromI8(*(LONGLONG*)src, LOCALE_USER_DEFAULT, 0, d);       break;
        case DBTYPE_UI8:         hr = VarBstrFromUI8(*(ULONGLONG*)src, LOCALE_USER_DEFAULT, 0, d);     break;
        case DBTYPE_GUID:
        {
            WCHAR szBuff[39];
            const GUID *id = (const GUID *)src;
            WCHAR format[] = {
                '{','%','0','8','X','-','%','0','4','X','-','%','0','4','X','-',
                '%','0','2','X','%','0','2','X','-',
                '%','0','2','X','%','0','2','X','%','0','2','X','%','0','2','X','%','0','2','X','%','0','2','X','}',0};
            wsprintfW(szBuff, format,
                id->Data1, id->Data2, id->Data3,
                id->Data4[0], id->Data4[1], id->Data4[2], id->Data4[3],
                id->Data4[4], id->Data4[5], id->Data4[6], id->Data4[7] );
            *d = SysAllocString(szBuff);
            hr = *d ? S_OK : E_OUTOFMEMORY;
        }
        break;
        case DBTYPE_BYTES:
        {
            *d = SysAllocStringLen(NULL, 2 * src_len);
            if (*d == NULL)
                hr = E_OUTOFMEMORY;
            else
            {
                const char hexchars[] = "0123456789ABCDEF";
                WCHAR *s = *d;
                unsigned char *p = src;
                while (src_len > 0)
                {
                    *s++ = hexchars[(*p >> 4) & 0x0F];
                    *s++ = hexchars[(*p)      & 0x0F];
                    src_len--; p++;
                }
                hr = S_OK;
            }
        }
        break;
        default: FIXME("Unimplemented conversion %04x -> BSTR\n", src_type); return E_NOTIMPL;
        }
        break;
    }

    case DBTYPE_UI1:
    {
        BYTE *d = dst;
        switch(src_type)
        {
        case DBTYPE_EMPTY:       *d = 0; hr = S_OK;                              break;
        case DBTYPE_I2:          hr = VarUI1FromI2(*(signed short*)src, d);      break;
        case DBTYPE_I4:          hr = VarUI1FromI4(*(signed int*)src, d);        break;
        case DBTYPE_R4:          hr = VarUI1FromR4(*(FLOAT*)src, d);             break;
        case DBTYPE_R8:          hr = VarUI1FromR8(*(double*)src, d);            break;
        case DBTYPE_CY:          hr = VarUI1FromCy(*(CY*)src, d);                break;
        case DBTYPE_DATE:        hr = VarUI1FromDate(*(DATE*)src, d);            break;
        case DBTYPE_BSTR:        hr = VarUI1FromStr(*(WCHAR**)src, LOCALE_USER_DEFAULT, 0, d); break;
        case DBTYPE_BOOL:        hr = VarUI1FromBool(*(VARIANT_BOOL*)src, d);    break;
        case DBTYPE_DECIMAL:     hr = VarUI1FromDec((DECIMAL*)src, d);           break;
        case DBTYPE_I1:          hr = VarUI1FromI1(*(signed char*)src, d);       break;
        case DBTYPE_UI1:         *d = *(BYTE*)src; hr = S_OK;                    break;
        case DBTYPE_UI2:         hr = VarUI1FromUI2(*(WORD*)src, d);             break;
        case DBTYPE_UI4:         hr = VarUI1FromUI4(*(DWORD*)src, d);            break;
        case DBTYPE_I8:          hr = VarUI1FromI8(*(LONGLONG*)src, d);          break;
        case DBTYPE_UI8:         hr = VarUI1FromUI8(*(ULONGLONG*)src, d);        break;
        default: FIXME("Unimplemented conversion %04x -> UI1\n", src_type); return E_NOTIMPL;
        }
        break;
    }
    case DBTYPE_UI2:
    {
        WORD *d = dst;
        switch(src_type)
        {
        case DBTYPE_EMPTY:       *d = 0; hr = S_OK;                              break;
        case DBTYPE_I2:          hr = VarUI2FromI2(*(signed short*)src, d);      break;
        case DBTYPE_I4:          hr = VarUI2FromI4(*(signed int*)src, d);        break;
        case DBTYPE_R4:          hr = VarUI2FromR4(*(FLOAT*)src, d);             break;
        case DBTYPE_R8:          hr = VarUI2FromR8(*(double*)src, d);            break;
        case DBTYPE_CY:          hr = VarUI2FromCy(*(CY*)src, d);                break;
        case DBTYPE_DATE:        hr = VarUI2FromDate(*(DATE*)src, d);            break;
        case DBTYPE_BSTR:        hr = VarUI2FromStr(*(WCHAR**)src, LOCALE_USER_DEFAULT, 0, d); break;
        case DBTYPE_BOOL:        hr = VarUI2FromBool(*(VARIANT_BOOL*)src, d);    break;
        case DBTYPE_DECIMAL:     hr = VarUI2FromDec((DECIMAL*)src, d);           break;
        case DBTYPE_I1:          hr = VarUI2FromI1(*(signed char*)src, d);       break;
        case DBTYPE_UI1:         hr = VarUI2FromUI1(*(BYTE*)src, d);             break;
        case DBTYPE_UI2:         *d = *(WORD*)src; hr = S_OK;                     break;
        case DBTYPE_UI4:         hr = VarUI2FromUI4(*(DWORD*)src, d);            break;
        case DBTYPE_I8:          hr = VarUI2FromI8(*(LONGLONG*)src, d);          break;
        case DBTYPE_UI8:         hr = VarUI2FromUI8(*(ULONGLONG*)src, d);        break;
        default: FIXME("Unimplemented conversion %04x -> UI2\n", src_type); return E_NOTIMPL;
        }
        break;
    }

    case DBTYPE_UI4:
    {
        DWORD *d = dst;
        switch(src_type)
        {
        case DBTYPE_EMPTY:       *d = 0; hr = S_OK;                              break;
        case DBTYPE_I2:          hr = VarUI4FromI2(*(signed short*)src, d);      break;
        case DBTYPE_I4:          hr = VarUI4FromI4(*(signed int*)src, d);        break;
        case DBTYPE_R4:          hr = VarUI4FromR4(*(FLOAT*)src, d);             break;
        case DBTYPE_R8:          hr = VarUI4FromR8(*(double*)src, d);            break;
        case DBTYPE_CY:          hr = VarUI4FromCy(*(CY*)src, d);                break;
        case DBTYPE_DATE:        hr = VarUI4FromDate(*(DATE*)src, d);            break;
        case DBTYPE_BSTR:        hr = VarUI4FromStr(*(WCHAR**)src, LOCALE_USER_DEFAULT, 0, d); break;
        case DBTYPE_BOOL:        hr = VarUI4FromBool(*(VARIANT_BOOL*)src, d);    break;
        case DBTYPE_DECIMAL:     hr = VarUI4FromDec((DECIMAL*)src, d);           break;
        case DBTYPE_I1:          hr = VarUI4FromI1(*(signed char*)src, d);       break;
        case DBTYPE_UI1:         hr = VarUI4FromUI1(*(BYTE*)src, d);             break;
        case DBTYPE_UI2:         hr = VarUI4FromUI2(*(WORD*)src, d);             break;
        case DBTYPE_UI4:         *d = *(DWORD*)src; hr = S_OK;                   break;
        case DBTYPE_I8:          hr = VarUI4FromI8(*(LONGLONG*)src, d);          break;
        case DBTYPE_UI8:         hr = VarUI4FromUI8(*(ULONGLONG*)src, d);        break;
        default: FIXME("Unimplemented conversion %04x -> UI4\n", src_type); return E_NOTIMPL;
        }
        break;
    }

    case DBTYPE_UI8:
    {
        ULONGLONG *d = dst;
        switch(src_type)
        {
        case DBTYPE_EMPTY:       *d = 0; hr = S_OK;                              break;
        case DBTYPE_I2:          hr = VarUI8FromI2(*(signed short*)src, d);      break;
        case DBTYPE_I4:          {LONGLONG s = *(signed int*)src; hr = VarUI8FromI8(s, d);        break;}
        case DBTYPE_R4:          hr = VarUI8FromR4(*(FLOAT*)src, d);             break;
        case DBTYPE_R8:          hr = VarUI8FromR8(*(double*)src, d);            break;
        case DBTYPE_CY:          hr = VarUI8FromCy(*(CY*)src, d);                break;
        case DBTYPE_DATE:        hr = VarUI8FromDate(*(DATE*)src, d);            break;
        case DBTYPE_BSTR:        hr = VarUI8FromStr(*(WCHAR**)src, LOCALE_USER_DEFAULT, 0, d); break;
        case DBTYPE_BOOL:        hr = VarUI8FromBool(*(VARIANT_BOOL*)src, d);    break;
        case DBTYPE_DECIMAL:     hr = VarUI8FromDec((DECIMAL*)src, d);           break;
        case DBTYPE_I1:          hr = VarUI8FromI1(*(signed char*)src, d);       break;
        case DBTYPE_UI1:         hr = VarUI8FromUI1(*(BYTE*)src, d);             break;
        case DBTYPE_UI2:         hr = VarUI8FromUI2(*(WORD*)src, d);             break;
        case DBTYPE_UI4:         hr = VarUI8FromUI4(*(DWORD*)src, d);            break;
        case DBTYPE_I8:          hr = VarUI8FromI8(*(LONGLONG*)src, d);          break;
        case DBTYPE_UI8:         *d = *(ULONGLONG*)src; hr = S_OK;               break;
        default: FIXME("Unimplemented conversion %04x -> UI8\n", src_type); return E_NOTIMPL;
        }
        break;
    }

    case DBTYPE_FILETIME:
    {
        FILETIME *d = dst;
        switch(src_type)
        {
        case DBTYPE_EMPTY:       d->dwLowDateTime = d->dwHighDateTime = 0; hr = S_OK;    break;
        case DBTYPE_FILETIME:    *d = *(FILETIME*)src; hr = S_OK;                        break;
        default: FIXME("Unimplemented conversion %04x -> FILETIME\n", src_type); return E_NOTIMPL;
        }
        break;
    }

    case DBTYPE_GUID:
    {
        GUID *d = dst;
        switch(src_type)
        {
        case DBTYPE_EMPTY:       *d = GUID_NULL; hr = S_OK; break;
        case DBTYPE_GUID:        *d = *(GUID*)src; hr = S_OK; break;
        default: FIXME("Unimplemented conversion %04x -> GUID\n", src_type); return E_NOTIMPL;
        }
        break;
    }

    case DBTYPE_WSTR:
    {
        BSTR b;
        DBLENGTH bstr_len;
        INT bytes_to_copy;
        hr = IDataConvert_DataConvert(iface, src_type, DBTYPE_BSTR, src_len, &bstr_len,
                                      src, &b, sizeof(BSTR), src_status, dst_status,
                                      precision, scale, flags);
        if(hr != S_OK) return hr;
        bstr_len = SysStringLen(b);
        *dst_len = bstr_len * sizeof(WCHAR); /* Doesn't include size for '\0' */
        *dst_status = DBSTATUS_S_OK;
        bytes_to_copy = min(*dst_len + sizeof(WCHAR), dst_max_len);
        if(dst)
        {
            if(bytes_to_copy >= sizeof(WCHAR))
            {
                memcpy(dst, b, bytes_to_copy - sizeof(WCHAR));
                *((WCHAR*)dst + bytes_to_copy / sizeof(WCHAR) - 1) = 0;
                if(bytes_to_copy < *dst_len + sizeof(WCHAR))
                    *dst_status = DBSTATUS_S_TRUNCATED;
            }
            else
            {
                *dst_status = DBSTATUS_E_DATAOVERFLOW;
                hr = DB_E_ERRORSOCCURRED;
            }
        }
        SysFreeString(b);
        return hr;
    }
    case DBTYPE_STR:
    {
        BSTR b;
        DBLENGTH bstr_len;
        INT bytes_to_copy;
        hr = IDataConvert_DataConvert(iface, src_type, DBTYPE_BSTR, src_len, &bstr_len,
                                      src, &b, sizeof(BSTR), src_status, dst_status,
                                      precision, scale, flags);
        if(hr != S_OK) return hr;
        bstr_len = SysStringLen(b);
        *dst_len = bstr_len * sizeof(char); /* Doesn't include size for '\0' */
        *dst_status = DBSTATUS_S_OK;
        bytes_to_copy = min(*dst_len + sizeof(char), dst_max_len);
        if(dst)
        {
            if(bytes_to_copy >= sizeof(char))
            {
                WideCharToMultiByte(CP_ACP, 0, b, bytes_to_copy - sizeof(char), dst, dst_max_len, NULL, NULL);
                *((char *)dst + bytes_to_copy / sizeof(char) - 1) = 0;
                if(bytes_to_copy < *dst_len + sizeof(char))
                    *dst_status = DBSTATUS_S_TRUNCATED;
            }
            else
            {
                *dst_status = DBSTATUS_E_DATAOVERFLOW;
                hr = DB_E_ERRORSOCCURRED;
            }
        }
        SysFreeString(b);
        return hr;
    }

    case DBTYPE_BYREF | DBTYPE_WSTR:
    {
        BSTR b;
        WCHAR **d = dst;
        DBLENGTH bstr_len;
        hr = IDataConvert_DataConvert(iface, src_type, DBTYPE_BSTR, src_len, &bstr_len,
                                      src, &b, sizeof(BSTR), src_status, dst_status,
                                      precision, scale, flags);
        if(hr != S_OK) return hr;

        bstr_len = SysStringLen(b) * sizeof(WCHAR);
        *dst_len = bstr_len; /* Doesn't include size for '\0' */

        *d = CoTaskMemAlloc(bstr_len + sizeof(WCHAR));
        if(*d) memcpy(*d, b, bstr_len + sizeof(WCHAR));
        else hr = E_OUTOFMEMORY;
        SysFreeString(b);
        return hr;
    }

    default:
        FIXME("Unimplemented conversion %04x -> %04x\n", src_type, dst_type);
        return E_NOTIMPL;

    }

    if(hr == DISP_E_OVERFLOW)
    {
        *dst_status = DBSTATUS_E_DATAOVERFLOW;
        *dst_len = get_length(dst_type);
        hr = DB_E_ERRORSOCCURRED;
    }
    else if(hr == S_OK)
    {
        *dst_status = DBSTATUS_S_OK;
        *dst_len = get_length(dst_type);
    }

    return hr;
}
Ejemplo n.º 21
0
void CCurrencyConversionSamplePlugin::ChangeItems(const TCHAR* acode) {
  CComQIPtr<IGoogleDesktopDisplayPluginHelper> pluginHelper(m_pluginHelper);
  ATLVERIFY(SUCCEEDED(pluginHelper->RemoveAllContentItems()));
  unused(acode); // TODO: can be used to optimize redraw
  CString result;
  CStringArray tokens;
  Currencies::Tokenize(GetCurrencies(), &tokens);
  SYSTEMTIME systime = {0};
  GetSystemTime(&systime);
  ATLVERIFY(tokens.GetCount() % 2 == 0);
  for (int i = 0; i < (int)tokens.GetCount(); i += 2) {
    CString currency = tokens.GetAt(i);
    // create a new item
    CCurrencyConversionSamplePluginContentItemImpl *curItem = NULL;
    ATLVERIFY(SUCCEEDED(CCurrencyConversionSamplePluginContentItemImpl::
      CreateInstance(&curItem)));
    CComPtr<IGoogleDesktopDisplayContentItemHelper> itemHelper = NULL;
    curItem->GetUnknown()->QueryInterface(
      IID_IGoogleDesktopDisplayContentItemHelper,
      reinterpret_cast<void**>(&itemHelper));
    // and set it's properties
    UINT flags = GDD_CONTENT_ITEM_FLAG_TIME_ABSOLUTE;
    CString strHeading;
    double rate = m_currencies->GetExchangeRate(currency);
    {
      CString s;
      s.Format(_T("%s,%.6f,"), currency, rate);
      result += s;
    }
    if (rate != 0.0) {
      if (m_invert != VARIANT_FALSE) {
          strHeading.Format(_T("1 %s = %.5f USD"), currency, 1.0 / rate);
      } else {
        strHeading.Format(_T("1 USD = %.5f %s"), rate, currency);
      }
    }
    else
      strHeading.Format(_T("%s ..."), currency);
    CComBSTR snippet;
    snippet.Append(L"1 USD in ");
    snippet.Append(currency);
    CComBSTR source(L"www.google.com");
    CComBSTR heading(strHeading);
    CString tt;
    tt.Format(_T("%s - currency of %s"), Currencies::GetCurrencyName(currency),
        Currencies::GetCountries(currency));
    CComBSTR tooltip = tt;
    DATE timeCreated;
    SystemTimeToVariantTime(&systime, &timeCreated);
    // do the actual setting of props
    ATLVERIFY(SUCCEEDED(itemHelper->put_heading(heading)));
    ATLVERIFY(SUCCEEDED(itemHelper->put_tooltip(tooltip)));
    ATLVERIFY(SUCCEEDED(itemHelper->put_source(source)));
    ATLVERIFY(SUCCEEDED(itemHelper->put_time_created(timeCreated)));
    ATLVERIFY(SUCCEEDED(itemHelper->put_snippet(snippet)));
    ATLVERIFY(SUCCEEDED(itemHelper->put_flags(
      static_cast<GoogleDesktopDisplayContentItemFlags>(flags))));
    ATLVERIFY(SUCCEEDED(itemHelper->put_layout(
      static_cast<GoogleDesktopDisplayContentItemLayout>(
        GDD_CONTENT_ITEM_LAYOUT_NOWRAP_ITEMS))));
    CComQIPtr<IGoogleDesktopDisplayContentItem> item(itemHelper);
    // Show the item in the sidebar and optionally in the notification 
    // window if the sidebar is auto-hidden.
    GoogleDesktopContentItemDisplayOptions item_flags = 
      static_cast<GoogleDesktopContentItemDisplayOptions>(
        GDD_ITEM_DISPLAY_IN_SIDEBAR | 
        GDD_ITEM_DISPLAY_AS_NOTIFICATION_IF_SIDEBAR_HIDDEN);
    ATLVERIFY(SUCCEEDED(pluginHelper->AddContentItem(item, item_flags)));
  }
  // if we are in minimized mode, update the title with latest info.
  GoogleDesktopDisplayTileDisplayState display_state = 
      GDD_TILE_DISPLAY_STATE_RESTORED;
  CComQIPtr<IGoogleDesktopDisplaySite> sidebar_site(m_spUnkSite);
  if (sidebar_site != NULL) // will be NULL during init time
    ATLVERIFY(SUCCEEDED(sidebar_site->get_display_state(&display_state)));

  if (display_state == GDD_TILE_DISPLAY_STATE_MINIMIZED)
    UpdateTitle(false);

  m_firstTime = false;
  int n = result.GetLength();
  if (n > 0 && result.GetAt(n - 1) == L',') {
    result = result.Left(n - 1);
  }
  SysFreeString(m_bstrCurrencies);
  m_bstrCurrencies = SysAllocString(result);
}
Ejemplo n.º 22
0
WXDLLEXPORT bool wxConvertVariantToOle(const wxVariant& variant, VARIANTARG& oleVariant)
{
    VariantInit(&oleVariant);
    if (variant.IsNull())
    {
        oleVariant.vt = VT_NULL;
        return true;
    }

    wxString type(variant.GetType());


    if (type == wxT("long"))
    {
        oleVariant.vt = VT_I4;
        oleVariant.lVal = variant.GetLong() ;
    }
    // Original VC6 came with SDK too old to contain VARIANT::llVal declaration
    // and there doesn't seem to be any way to test for it as Microsoft simply
    // added it to the later version of oaidl.h without changing anything else.
    // So assume it's not present for VC6, even though it might be if an
    // updated SDK is used. In this case the user would need to disable this
    // check himself.
#if wxUSE_LONGLONG && !defined(__VISUALC6__)
    else if (type == wxT("longlong"))
    {
        oleVariant.vt = VT_I8;
        oleVariant.llVal = variant.GetLongLong().GetValue();
    }
#endif
    else if (type == wxT("char"))
    {
        oleVariant.vt=VT_I1;            // Signed Char
        oleVariant.cVal=variant.GetChar();
    }
    else if (type == wxT("double"))
    {
        oleVariant.vt = VT_R8;
        oleVariant.dblVal = variant.GetDouble();
    }
    else if (type == wxT("bool"))
    {
        oleVariant.vt = VT_BOOL;
        oleVariant.boolVal = variant.GetBool() ? VARIANT_TRUE : VARIANT_FALSE;
    }
    else if (type == wxT("string"))
    {
        wxString str( variant.GetString() );
        oleVariant.vt = VT_BSTR;
        oleVariant.bstrVal = wxConvertStringToOle(str);
    }
#if wxUSE_DATETIME
    else if (type == wxT("datetime"))
    {
        wxDateTime date( variant.GetDateTime() );
        oleVariant.vt = VT_DATE;

        SYSTEMTIME st;
        date.GetAsMSWSysTime(&st);

        SystemTimeToVariantTime(&st, &oleVariant.date);
    }
#endif
    else if (type == wxT("void*"))
    {
        oleVariant.vt = VT_DISPATCH;
        oleVariant.pdispVal = (IDispatch*) variant.GetVoidPtr();
    }
    else if (type == wxT("list"))
    {
        wxSafeArrayHelper sah;

        if (!sah.Create(VT_VARIANT, variant.GetCount()))
            return false;

        for (size_t i = 0; i < variant.GetCount(); i++)
        {
            if (!sah.SetElement(i, variant[i]))
                return false;
        }

        oleVariant.vt = VT_VARIANT | VT_ARRAY;
        oleVariant.parray = sah.Detach();
    }
    else if (type == wxT("arrstring"))
    {
        wxArrayString strings(variant.GetArrayString());
        wxSafeArrayHelper sah;

        if (!sah.Create(VT_BSTR, strings.GetCount()))
            return false;

        for (size_t i = 0; i < strings.GetCount(); i++)
        {
            if (!sah.SetElement(i, strings[i]))
                return false;
        }

        oleVariant.vt = VT_BSTR | VT_ARRAY;
        oleVariant.parray = sah.Detach();
    }
    else
    {
        oleVariant.vt = VT_NULL;
        return false;
    }
    return true;
}
Ejemplo n.º 23
0
/////////////////////////////////////////////////////////////////////
// OPCGroup::SyncRead method
STDMETHODIMP COPCGroupImpl::SyncRead( SHORT Source,
                        LONG NumItems,
                        SAFEARRAY ** ppServerHandles,
                        SAFEARRAY ** ppValues,
                        SAFEARRAY ** ppErrors,
                        VARIANT *pQualities,    // \/ Optional \/
                        VARIANT *pTimeStamps)
{
   // Validate input types
   if(*ppServerHandles == NULL)
      return E_INVALIDARG;
   if(ppValues == NULL)
      return E_INVALIDARG;
   if(ppErrors == NULL)
      return E_INVALIDARG;

   if( !m_pSyncIO )
   {
      m_pSyncIO = m_pOPCGroup;   // get Sync interface
      if( !m_pSyncIO )
         return E_FAIL;
   }

   HRESULT hr = S_OK;
   LONG lBound=0;
   LONG uBound=0;
   hr = SafeArrayGetLBound(*ppServerHandles, 1, &lBound);
   if( FAILED(hr) )
      return hr;
   hr = SafeArrayGetUBound(*ppServerHandles, 1, &uBound);
   if( FAILED(hr) )
      return hr;
   if( lBound > 1 )
      return E_INVALIDARG;
   if( uBound < NumItems )
      return E_INVALIDARG;

   // Create array of handles
   OPCHANDLE* pSHandles = (OPCHANDLE*)_alloca(NumItems*sizeof(OPCHANDLE));
   memset( pSHandles, 0, NumItems*sizeof(OPCHANDLE) );
   for( long index=0; index<NumItems; index++ )
      {
      LONG vbIndex = index+1;
      DWORD localHandle=0;
      hr = SafeArrayGetElement(*ppServerHandles, &vbIndex, &localHandle);
      if( FAILED(hr) )
         return hr;
      COPCItem* pItem = (COPCItem*)localHandle;
//      if( !m_items.Lookup( (LPVOID)localHandle, pItem ) )
//         return E_INVALIDARG;
      pSHandles[index] = pItem->GetServerHandle();
      }

   // call the server
   OPCITEMSTATE* pItemState;
   HRESULT *pErrors=0;
   hr = m_pSyncIO->Read( (OPCDATASOURCE)Source,
                         (DWORD)NumItems,
                         pSHandles,
                         &pItemState,
                         &pErrors);
   if( FAILED( hr ) )
   {
      return hr;
   }

   // Return Values in a SAFEARRAY and update each COPCItem
   {
      SAFEARRAYBOUND bound;
      bound.lLbound = 1;
      bound.cElements = NumItems;
      SAFEARRAY *pArray = SafeArrayCreate(VT_VARIANT, 1, &bound);
      if(pArray == NULL)
         return E_FAIL;    // temp
      for( long index=0; index<NumItems; index++ )
      {
         LONG vbIndex = index+1;
         VariantToAutomation(&pItemState[index].vDataValue);
         SafeArrayPutElement(pArray, &vbIndex, (void *)&pItemState[index].vDataValue);
         if( SUCCEEDED(pErrors[index]) )
         {
            COPCItem* pItem = (COPCItem*)pItemState[index].hClient;
            pItem->Update( &pItemState[index] );
         }
         VariantClear( &pItemState[index].vDataValue );
      }
      *ppValues = pArray;
   }

   // Return errors in a SAFEARRAY
   {
      SAFEARRAYBOUND bound;
      bound.lLbound = 1;
      bound.cElements = NumItems;
      SAFEARRAY *pArray = SafeArrayCreate(VT_I4, 1, &bound);
      if(pArray == NULL)
         return E_FAIL;    // temp
      for( long index=0; index<NumItems; index++ )
      {
         LONG vbIndex = index+1;
         SafeArrayPutElement(pArray, &vbIndex, (void *)&pErrors[index]);
      }
      *ppErrors = pArray;
   }

   // Return qualities in a SAFEARRAY
   if(pQualities != NULL && pQualities->scode != DISP_E_PARAMNOTFOUND )
   {
      VariantClear( pQualities );
      SAFEARRAYBOUND bound;
      bound.lLbound = 1;
      bound.cElements = NumItems;
      SAFEARRAY *pArray = SafeArrayCreate(VT_I2, 1, &bound);
      if(pArray == NULL)
         return E_FAIL;    // temp
      for( long index=0; index<NumItems; index++ )
      {
         LONG vbIndex = index+1;
         SafeArrayPutElement(pArray, &vbIndex, (void *)&pItemState[index].wQuality);
      }
      pQualities->vt = VT_I2 | VT_ARRAY;
      pQualities->parray = pArray;
   }

   // Return timestamps in a SAFEARRAY
   if(pTimeStamps != NULL && pTimeStamps->scode != DISP_E_PARAMNOTFOUND )
   {
      VariantClear( pTimeStamps );
      SAFEARRAYBOUND bound;
      bound.lLbound = 1;
      bound.cElements = NumItems;
      SAFEARRAY *pArray = SafeArrayCreate(VT_DATE, 1, &bound);
      if(pArray == NULL)
         return E_FAIL;    // temp
      for( long index=0; index<NumItems; index++ )
      {
         LONG vbIndex = index+1;
         DATE timeStamp = NULL; 
         FILETIME filetimeLocal;
         if( FileTimeToLocalFileTime( &pItemState[index].ftTimeStamp, &filetimeLocal) )
         {
            SYSTEMTIME systime;
            if( FileTimeToSystemTime(&filetimeLocal, &systime) )
            {
	            SystemTimeToVariantTime( &systime, &timeStamp);
	         }
         }
         SafeArrayPutElement(pArray, &vbIndex, (void *)&timeStamp);
      }
      pTimeStamps->vt = VT_DATE | VT_ARRAY;
      pTimeStamps->parray = pArray;
   }

   CoTaskMemFree( pItemState );
   CoTaskMemFree( pErrors );

   return S_OK;
}
Ejemplo n.º 24
0
WXDLLEXPORT bool wxConvertVariantToOle(const wxVariant& variant, VARIANTARG& oleVariant)
{
    VariantInit(&oleVariant);
    if (variant.IsNull())
    {
        oleVariant.vt = VT_NULL;
        return true;
    }

    wxString type(variant.GetType());

    if (type == wxT("errorcode"))
    {
        wxVariantDataErrorCode* const
            ec = wxStaticCastVariantData(variant.GetData(),
                                         wxVariantDataErrorCode);
        oleVariant.vt = VT_ERROR;
        oleVariant.scode = ec->GetValue();
    }
    else if (type == wxT("currency"))
    {
        wxVariantDataCurrency* const
            c = wxStaticCastVariantData(variant.GetData(),
                                        wxVariantDataCurrency);
        oleVariant.vt = VT_CY;
        oleVariant.cyVal = c->GetValue();
    }
    else if (type == wxT("safearray"))
    {
        wxVariantDataSafeArray* const
            vsa = wxStaticCastVariantData(variant.GetData(),
                                          wxVariantDataSafeArray);
        SAFEARRAY* psa = vsa->GetValue();
        VARTYPE vt;

        wxCHECK(psa, false);
        HRESULT hr = SafeArrayGetVartype(psa, &vt);
        if ( FAILED(hr) )
        {
            wxLogApiError(wxS("SafeArrayGetVartype()"), hr);
            SafeArrayDestroy(psa);
            return false;
        }
        oleVariant.vt = vt | VT_ARRAY;
        oleVariant.parray = psa;
    }
    else if (type == wxT("long"))
    {
        oleVariant.vt = VT_I4;
        oleVariant.lVal = variant.GetLong() ;
    }
    // Original VC6 came with SDK too old to contain VARIANT::llVal declaration
    // and there doesn't seem to be any way to test for it as Microsoft simply
    // added it to the later version of oaidl.h without changing anything else.
    // So assume it's not present for VC6, even though it might be if an
    // updated SDK is used. In this case the user would need to disable this
    // check himself.
#if wxUSE_LONGLONG && !defined(__VISUALC6__)
    else if (type == wxT("longlong"))
    {
        oleVariant.vt = VT_I8;
        oleVariant.llVal = variant.GetLongLong().GetValue();
    }
#endif
    else if (type == wxT("char"))
    {
        oleVariant.vt=VT_I1;            // Signed Char
        oleVariant.cVal=variant.GetChar();
    }
    else if (type == wxT("double"))
    {
        oleVariant.vt = VT_R8;
        oleVariant.dblVal = variant.GetDouble();
    }
    else if (type == wxT("bool"))
    {
        oleVariant.vt = VT_BOOL;
        oleVariant.boolVal = variant.GetBool() ? VARIANT_TRUE : VARIANT_FALSE;
    }
    else if (type == wxT("string"))
    {
        wxString str( variant.GetString() );
        oleVariant.vt = VT_BSTR;
        oleVariant.bstrVal = wxConvertStringToOle(str);
    }
#if wxUSE_DATETIME
    else if (type == wxT("datetime"))
    {
        wxDateTime date( variant.GetDateTime() );
        oleVariant.vt = VT_DATE;

        SYSTEMTIME st;
        date.GetAsMSWSysTime(&st);

        SystemTimeToVariantTime(&st, &oleVariant.date);
    }
#endif
    else if (type == wxT("void*"))
    {
        oleVariant.vt = VT_DISPATCH;
        oleVariant.pdispVal = (IDispatch*) variant.GetVoidPtr();
    }
    else if (type == wxT("list"))
    {
        wxSafeArray<VT_VARIANT> safeArray;
        if (!safeArray.CreateFromListVariant(variant))
            return false;

        oleVariant.vt = VT_VARIANT | VT_ARRAY;
        oleVariant.parray = safeArray.Detach();
    }
    else if (type == wxT("arrstring"))
    {
        wxSafeArray<VT_BSTR> safeArray;

        if (!safeArray.CreateFromArrayString(variant.GetArrayString()))
            return false;

        oleVariant.vt = VT_BSTR | VT_ARRAY;
        oleVariant.parray = safeArray.Detach();
    }
    else
    {
        oleVariant.vt = VT_NULL;
        return false;
    }
    return true;
}
Ejemplo n.º 25
0
void CNetLogViewer::Execute(void*)
{
TRY_CATCH

	/// Adding internal clients for tests
	/*{
		INetLogClient* newClient;
		tstring clientName;
		clientName = Format(_T("%s:%s"),"192.168.0.5","iexplore.exe");
		SYSTEMTIME sysTime = static_cast<SYSTEMTIME>(cDate().GetNow().AddCountDays(0));
		DATE date;
		SystemTimeToVariantTime(&sysTime,&date);
		CNetLogClient::CreateInstance(&newClient);
		newClient->put_RecentReply(date);
		newClient->put_Name(CComBSTR(clientName.c_str()));
		newClient->put_IP(CComBSTR("192.168.0.5"));
		m_clients[clientName] = newClient;
		OnClientFound(newClient);
	}
	{
		INetLogClient* newClient;
		tstring clientName;
		clientName = Format(_T("%s:%s"),"192.168.0.3","NWLTest.exe");
		SYSTEMTIME sysTime = static_cast<SYSTEMTIME>(cDate().GetNow().AddCountDays(1));
		DATE date;
		SystemTimeToVariantTime(&sysTime,&date);
		CNetLogClient::CreateInstance(&newClient);
		newClient->put_RecentReply(date);
		newClient->put_Name(CComBSTR(clientName.c_str()));
		newClient->put_IP(CComBSTR("192.168.0.3"));
		m_clients[clientName] = newClient;
		OnClientFound(newClient);
	}*/

	
	/// Last bCast send time
	cDate lastBCast;
	tstring fromIp;
	unsigned int fromPort;
	char buf[MAX_PATH + 1];
	buf[MAX_PATH] = 0;
	INetLogClient* newClient;
	tstring clientName;
	std::map<tstring, CComPtr<INetLogClient> >::iterator client;
	while(!Terminated())
	{
		/// Freing time quant
		/// Sleep is used instead of SwitchToThread(), cause it forces Dispatcher to switch context
		/// while SwitchToThread switches context only there are scheduled threads
		/// and whis is totally not what we want, cause it will result in 100% CPU usage
		Sleep(1); 	
		
		/// Sending broadcast request
		if (lastBCast < cDate().GetNow().AddMilliSecs(0 - REQUESTS_INTERVAL))
		{
			SendBroadCastRequest();
			lastBCast.GetNow();
			//(cMsgBoxLog()).Add(_MESSAGE_,"BCast sent");

			if (Terminated())
				break;
			/// Cleaning up timed out clients
			CleanUpTimedOutClients();
		}

		if (Terminated())
			break;
		/// Receiving alive replys from clients
		SUDPListenerMsg *msg;
		while (m_udpSocket.GetReadyDataCount())
		{
			memset(buf,0,MAX_PATH); /// TODO:remove
			if (SOCKET_ERROR == m_udpSocket.ReceiveFrom(fromIp, fromPort, buf, MAX_PATH))
			{
				Log.Add(MCSocketStreamException(_T("failed to m_udpSocket.ReceiveFrom")));
				break;
			}
			/// Creating client
			msg = reinterpret_cast<SUDPListenerMsg*>(buf);
			clientName = Format(_T("%s:%d at %s"), msg->m_data, msg->m_process, fromIp.c_str());
			client = m_clients.find(clientName);
			if (client != m_clients.end())
			{
				SYSTEMTIME sysTime = static_cast<SYSTEMTIME>(cDate().GetNow());
				DATE date;
				SystemTimeToVariantTime(&sysTime,&date);
				client->second->put_RecentReply(date);
				client->second->put_TCPPort(msg->m_tcpPort);
				//client
			} else
			{
				CNetLogClient::CreateInstance(&newClient);
				newClient->put_Name(CComBSTR(clientName.c_str()));
				newClient->put_IP(CComBSTR(fromIp.c_str()));
				newClient->put_TCPPort(msg->m_tcpPort);
				m_clients[clientName] = newClient;
				OnClientFound(newClient);
			}
		}
	}

CATCH_LOG()
}
STDMETHODIMP CSolidworksCrawlPlugin::HandleFile(BSTR full_path_to_file, IDispatch* event_factory)
{
	// Event factory object to handle the passed in pointer from Google Desktop.
	CComPtr<IGoogleDesktopEventFactory> mcEventFactory;

	// Used to create an event object for this file to send back to Google Desktop.
	CComPtr<IDispatch> mcEventDisp;

	HRESULT hr;

	hr  = event_factory->QueryInterface(&mcEventFactory); // Get the event factory
	if (FAILED(hr))
		return Error(L"No event factory", IID_ISolidworksCrawlPlugin, hr);

	// Replace "Google.Desktop.TextFile" with the appropriate schema for your file.
	hr = mcEventFactory->CreateEvent(CComBSTR(CLSID_SolidworksCrawlPlugin),
		CComBSTR(L"Google.Desktop.TextFile"), &mcEventDisp);
	if (FAILED(hr))
		return Error(L"Unable to create event", IID_ISolidworksCrawlPlugin, hr);

	CComQIPtr<IGoogleDesktopEvent> mcEvent(mcEventDisp);

	ATLASSERT(mcEventDisp && mcEvent);
	if (mcEvent == NULL)
		return Error(L"Event does not implement IGoogleDesktopEvent", IID_ISolidworksCrawlPlugin, E_UNEXPECTED);

	// Get indexable content from the file.
	// Set the event object's properties.
	// Send the event object to Google Desktop.

	WIN32_FIND_DATA wfd;
	if (!GetFileAttributesEx(full_path_to_file, GetFileExInfoStandard, &wfd))
		return HRESULT_FROM_WIN32(::GetLastError());

	SYSTEMTIME systemTime;
	FileTimeToSystemTime(&wfd.ftCreationTime, &systemTime);

	// convert the date to the variant format
	double varDate;
	SystemTimeToVariantTime(&systemTime, &varDate);

	hr = mcEvent->AddProperty(CComBSTR(L"uri"), CComVariant(full_path_to_file));
	if (FAILED(hr))
		return Error(L"AddProperty uri failed", IID_ISolidworksCrawlPlugin, hr);

	hr = mcEvent->AddProperty(CComBSTR(L"last_modified_time"), CComVariant(varDate, VT_DATE));
	if (FAILED(hr))
		return Error(L"AddProperty last_modified_time failed", IID_ISolidworksCrawlPlugin, hr);

	hr = mcEvent->AddProperty(CComBSTR(L"format"), CComVariant("text/plain"));
	if (FAILED(hr))
		return Error(L"AddProperty format failed", IID_ISolidworksCrawlPlugin, hr);

	// Initialize COM and create an instance of the InterfaceImplementation class:
	IManagedInterface *cpi = NULL;
	hr = CoCreateInstance(CLSID_IFilterFileReader,
		NULL, CLSCTX_INPROC_SERVER,
		IID_IManagedInterface, reinterpret_cast<void**>(&cpi));
	if (FAILED(hr))
	{
		return Error(L"Couldn't create the instanced", IID_ISolidworksCrawlPlugin, hr);
	}

	hr = cpi->loadFile(full_path_to_file);
	if (FAILED(hr))
	{
		return Error(L"Couldn't loadFile", IID_ISolidworksCrawlPlugin, hr);
	}

	hr = mcEvent->AddProperty(CComBSTR(L"content"), CComVariant(cpi->readFile().GetBSTR()));
	if (FAILED(hr))
		return Error(L"AddProperty content failed", IID_ISolidworksCrawlPlugin, hr);

	cpi->Release();
	cpi = NULL;

	hr = mcEvent->Send(EventFlagIndexable);
	if (FAILED(hr))
		return Error(L"Send failed", IID_ISolidworksCrawlPlugin, hr);

	return hr;
}
Ejemplo n.º 27
0
void CTeenSpiritDlg::OnTimer(UINT nIDEvent)
{
	PrgAPI* pAPI = PRGAPI();
	SQLManager* pSM = pAPI->GetSQLManager();
	switch (nIDEvent)
	{
	case TMR_InitialDelay:
		SetTimer(TMR_PlayerMonitor, PLAYERMONITOR_TIMER_DELAY, NULL);
		pAPI->GetTrayToolTipDlg();
		KillTimer(nIDEvent);
		{
			TracksFilter tf;
			if (pSM->GetTrackCount(tf) == 0)
			{
				TCHAR url[1000];
				pAPI->GetSiteURL(url, 1000, PrgAPI::SA_Help, _T("emptycollection"));
				CMessageDlg dlg(this);
				dlg.SetText(CMessageDlg::TT_Title, pAPI->GetString(IDS_EMPTYCOLLECTION_TITLE));
				dlg.SetText(CMessageDlg::TT_SubTitle, pAPI->GetString(IDS_EMPTYCOLLECTION_DETAIL));
				dlg.SetHelpLink(pAPI->GetString(IDS_HELP_S), url);
				dlg.SetText(CMessageDlg::TT_ButtonRight, pAPI->GetString(IDS_OK));
				switch (dlg.DoModal())
				{
				case CMessageDlg::RES_Close:
					pAPI->GoToSiteURL(PrgAPI::SA_Help, _T("emptycollection"));
					break;
				case CMessageDlg::RES_Right:
					pAPI->GetActionManager()->ShowAddNewCollectionDlg(this);
					UpdateWindow();
					break;
				}
			}
			if (pAPI->GetOption(OPT_GEN_UseNativeOnlineServices) == -1)
			{
				CMessageDlg dlg(this);
				
				dlg.SetText(CMessageDlg::TT_Title, pAPI->GetString(IDS_OPTIONS));
				dlg.SetText(CMessageDlg::TT_SubTitle, pAPI->GetString(IDS_CONFIRMATION));
				TCHAR bf[1000];
				_sntprintf(bf, 1000, _T("%s (beta)"), pAPI->GetString(IDS_TSONLINESERVICES));
				dlg.SetText(CMessageDlg::TT_CheckBox, bf);
				pAPI->GetSiteURL(bf, 1000, PrgAPI::SA_Navigate, _T("onlineservices-about"));
				dlg.SetHelpLink(pAPI->GetString(IDS_HELP_S), bf);
				dlg.SetCheck(TRUE);
				dlg.SetText(CMessageDlg::TT_ButtonRight, pAPI->GetString(IDS_OK));
				if (dlg.DoModal() != CMessageDlg::RES_Close)
					pAPI->SetOption(OPT_GEN_UseNativeOnlineServices, dlg.IsChecked() ? 1 : 0);
			}
			MediaPlayer* pPlayer = PRGAPI()->GetMediaPlayer();
			m_playerBar.SetMediaPlayer(pPlayer);
			if (pAPI->GetOption(OPT_MINIPLR_ShowAtStartup) != 0)
				pAPI->GetMiniPlayerDlg(TRUE)->Show();
		}
		break;
	case TMR_CheckNewVersion:
		KillTimer(nIDEvent);
		if (pAPI->GetOption(OPT_GEN_CheckForUpdates))
		{
			PrgAPI* pAPI = PRGAPI();
			SYSTEMTIME st;
			GetLocalTime(&st);
			DOUBLE thisDay;
			SystemTimeToVariantTime(&st, &thisDay);
			if (INT(thisDay) - pAPI->GetOption(OPT_GEN_CheckLastCheck) >= pAPI->GetOption(OPT_GEN_DaysBetweenCheck))
			{
				pAPI->SetOption(OPT_GEN_CheckLastCheck, INT(thisDay));
				AfxBeginThread(&NewVersionCheckThreadST, (void*)this ,0 ,0 ,0);
			}
		}
		break;
	case TMR_AutoUpdateDB:
		KillTimer(nIDEvent);
		if (pAPI->GetOption(OPT_GEN_AutoUpdateDB) != 0)
			pAPI->GetCollectionManager()->RefreshLocalCollections(TRUE, FALSE, TRUE);
		break;
	//case COLLECTIONREFRESH_TIMER:
	//	{
	//		PrgAPI* pAPI = PRGAPI();
	//		CollectionManager* pCM = pAPI->GetCollectionManager();
	//		if (pCM->GetState() == CollectionManager::S_Working)
	//		{
	//			const CollectionUpdateJob::Progress prog = pCM->GetProgress();
	//			INT curVal = prog.curPos;
	//			if (curVal - m_lastUpdateActionsPerformed > 100)
	//			{
	//				m_lastUpdateActionsPerformed = curVal;
	//			}
	//		}
	//		else
	//			KillTimer(nIDEvent);
	//	}
	//	break;
	case TMR_HeartBeat://Used by BaseDirector for Send/Post Messages
		pAPI->GetStateManager()->HeartBeat();
		break;
	case TMR_AppMonitor://Used for History Tracking, Download Status Update etc
		pAPI->Monitor();
		break;
	case TMR_PlayerMonitor:
		{
			MediaPlayer::Changes changes = pAPI->GetMediaPlayer()->GetChanges();
			if (changes.tickPlayList >= m_monitorPlayerTick)
				pAPI->GetStateManager()->SendMessage(SM_PlayListChanged);
			if (changes.tickMediaChanged >= m_monitorPlayerTick && m_monitorPlayerTick > 0)
				pAPI->GetStateManager()->SendMessage(SM_MediaChanged);
			m_monitorPlayerTick = GetTickCount();
		}
		break;
	case TMR_ShowTrayTooltipOnMouseMove:
		{
			KillTimer(nIDEvent);
			CPoint ptCurPos;
			GetCursorPos(&ptCurPos);
			if (ptCurPos == m_ptTrayCursorPos)
			{
				pAPI->GetTrayToolTipDlg()->OnMouseOverTray(ptCurPos);
			}
		}
		break;
	default:
		CDialog::OnTimer(nIDEvent);
		break;
	}

}
Ejemplo n.º 28
0
WXDLLEXPORT bool wxConvertVariantToOle(const wxVariant& variant, VARIANTARG& oleVariant)
{
    VariantInit(&oleVariant);
    if (variant.IsNull())
    {
        oleVariant.vt = VT_NULL;
        return true;
    }

    wxString type(variant.GetType());

    if (type == wxT("errorcode"))
    {
        wxVariantDataErrorCode* const
            ec = wxStaticCastVariantData(variant.GetData(),
                                         wxVariantDataErrorCode);
        oleVariant.vt = VT_ERROR;
        oleVariant.scode = ec->GetValue();
    }
    else if (type == wxT("currency"))
    {
        wxVariantDataCurrency* const
            c = wxStaticCastVariantData(variant.GetData(),
                                        wxVariantDataCurrency);
        oleVariant.vt = VT_CY;
        oleVariant.cyVal = c->GetValue();
    }
    else if (type == wxT("safearray"))
    {
        wxVariantDataSafeArray* const
            vsa = wxStaticCastVariantData(variant.GetData(),
                                          wxVariantDataSafeArray);
        SAFEARRAY* psa = vsa->GetValue();
        VARTYPE vt;

        wxCHECK(psa, false);
        HRESULT hr = SafeArrayGetVartype(psa, &vt);
        if ( FAILED(hr) )
        {
            wxLogApiError(wxS("SafeArrayGetVartype()"), hr);
            SafeArrayDestroy(psa);
            return false;
        }
        oleVariant.vt = vt | VT_ARRAY;
        oleVariant.parray = psa;
    }
    else if (type == wxT("long"))
    {
        oleVariant.vt = VT_I4;
        oleVariant.lVal = variant.GetLong() ;
    }
#if wxUSE_LONGLONG
    else if (type == wxT("longlong"))
    {
        oleVariant.vt = VT_I8;
        oleVariant.llVal = variant.GetLongLong().GetValue();
    }
#endif
    else if (type == wxT("char"))
    {
        oleVariant.vt=VT_I1;            // Signed Char
        oleVariant.cVal=variant.GetChar();
    }
    else if (type == wxT("double"))
    {
        oleVariant.vt = VT_R8;
        oleVariant.dblVal = variant.GetDouble();
    }
    else if (type == wxT("bool"))
    {
        oleVariant.vt = VT_BOOL;
        oleVariant.boolVal = variant.GetBool() ? VARIANT_TRUE : VARIANT_FALSE;
    }
    else if (type == wxT("string"))
    {
        wxString str( variant.GetString() );
        oleVariant.vt = VT_BSTR;
        oleVariant.bstrVal = wxConvertStringToOle(str);
    }
#if wxUSE_DATETIME
    else if (type == wxT("datetime"))
    {
        wxDateTime date( variant.GetDateTime() );
        oleVariant.vt = VT_DATE;

        SYSTEMTIME st;
        date.GetAsMSWSysTime(&st);

        SystemTimeToVariantTime(&st, &oleVariant.date);
    }
#endif
    else if (type == wxT("void*"))
    {
        oleVariant.vt = VT_DISPATCH;
        oleVariant.pdispVal = (IDispatch*) variant.GetVoidPtr();
    }
    else if (type == wxT("list"))
    {
        wxSafeArray<VT_VARIANT> safeArray;
        if (!safeArray.CreateFromListVariant(variant))
            return false;

        oleVariant.vt = VT_VARIANT | VT_ARRAY;
        oleVariant.parray = safeArray.Detach();
    }
    else if (type == wxT("arrstring"))
    {
        wxSafeArray<VT_BSTR> safeArray;

        if (!safeArray.CreateFromArrayString(variant.GetArrayString()))
            return false;

        oleVariant.vt = VT_BSTR | VT_ARRAY;
        oleVariant.parray = safeArray.Detach();
    }
    else
    {
        oleVariant.vt = VT_NULL;
        return false;
    }
    return true;
}
void OnClick(char* lpszPictureName, char* lpszObjectName, char* lpszPropertyName)
{
#define NumberOfData 7
// порядок наименования газов в массивах:
// 0 - CO2
// 1 -  CO
// 2 - NOx
// 3 - NO
// 4 - NO2
// 5 - SO2
// 6 - запыленность


// подключаем функции для работы со временем
#pragma code ("oleaut32.dll")
INT SystemTimeToVariantTime(LPSYSTEMTIME lpSystemTime, double *pvtime);
INT VariantTimeToSystemTime(double vtime, LPSYSTEMTIME lpSystemTime);
#pragma code ()

// структуры для времени начальной и конечной дат
SYSTEMTIME TimeFrom, TimeTo;
// выбранные из WinCC день, месяц, год
WORD day, month, year;
// строки для представления начальной даты, конечной даты, обоих дат
char date_begin[20], date_end[20], date_range[60];
// для перевода из SystemTime в VariantTime и обратно
double date;
// массивы выбросов из архива, выбросов за простой, суммарных выбросов, средних выбросов, максимальных выбросов
double emisArchive[NumberOfData], emisStop[NumberOfData], emisTotal[NumberOfData], emisAvg[NumberOfData], emisMax[NumberOfData];
// массивы превышений и сумм превышений
double excess[10][NumberOfData], excessTotal[NumberOfData];
// время простоя
double timeBreak;
// процент превышений
double percent;
int i, j;
// выбранный тип отчета:
// 1 - выбросы за день
// 2 - выбросы за месяц
// 4 - выбросы за год
// 8 - превышения за день
// 16 - превышения за месяц
// 32 - превышения за год
long report_type;
// выбранное действие:
// 1 - показать
// 2 - печатать
long report_action;
BOOL fRet;
// массив данных из архива
PTLG_ARCHIVDATARAW ADR;
// количество данных из архива
DWORD Number;
// название архива
LPCTSTR lpszArchivName = "OS_SVR1::ProcessValueArchive";
// массив для имен тегов газов, время простоя
LPCTSTR lpszTagName[NumberOfData], lpszTagTimeBreak;
// массив тегов для суммарных выбросов
LPCTSTR lpszTagEmisArchive[NumberOfData], lpszTagEmisStop[NumberOfData], lpszTagEmisTotal[NumberOfData];
// двумерный массив для полей отчета по превышениям
LPCTSTR lpszExcess[10][NumberOfData], lpszExcessTotal[NumberOfData];
// имя отчета
LPCTSTR lpszReportName;


// деактивируем элементы
SetPropChar(lpszPictureName, "Report_Build", "Text", "Работаю...");
SetPropBOOL(lpszPictureName, "Report_Build", "Operation", 0);
SetPropBOOL(lpszPictureName, "2203AZ_Report_Type", "Operation", 0);
SetPropBOOL(lpszPictureName, "2203AZ_Report_Action", "Operation", 0);
SetPropBOOL(lpszPictureName, "2203AZ_Report_Day", "Operation", 0);
SetPropBOOL(lpszPictureName, "2203AZ_Report_Month", "Operation", 0);
SetPropBOOL(lpszPictureName, "2203AZ_Report_Year", "Operation", 0);

// скрываем столбцы Online Table Control
for (i = 0; i < 20; i++) {
	SetPropWord(lpszPictureName, "Table", "ValueColumnIndex", i);
	SetPropBOOL(lpszPictureName, "Table", "ValueColumnVisible", 0);
}

// считываем тип отчета
report_type = GetPropWord(lpszPictureName, "2203AZ_Report_Type", "Process");
report_action = GetPropWord(lpszPictureName, "2203AZ_Report_Action", "Process");

// считываем выбранную дату
day = GetTagWord("2203AZ_Report_Day");
month = GetTagWord("2203AZ_Report_Month");
year = GetTagWord("2203AZ_Report_Year");


// промежуток времени за день
if (report_type == 1 || report_type == 8) {
	// задаем начальную дату
	TimeFrom.wYear = year;
	TimeFrom.wMonth = month;
	TimeFrom.wDay = day;
	TimeFrom.wHour = 0;
	TimeFrom.wMinute = 0;
	TimeFrom.wSecond = 0;

	// прибавляем 1 день
	SystemTimeToVariantTime(&TimeFrom, &date);
	VariantTimeToSystemTime(date + 1, &TimeTo);
}


// промежуток времени за месяц
if (report_type == 2 || report_type == 16) {
	// задаем начальную дату
	TimeFrom.wYear = year;
	TimeFrom.wMonth = month;
	TimeFrom.wDay = 1;		// если нужен апрель - надо ставить 23 число
	TimeFrom.wHour = 0;
	TimeFrom.wMinute = 0;
	TimeFrom.wSecond = 0;

	// задаем конечную дату
	if (month == 12) {
		TimeTo.wYear = (WORD) ((INT)TimeFrom.wYear + 1);
		TimeTo.wMonth = 1;
	}
	else {
		TimeTo.wYear = TimeFrom.wYear;
		TimeTo.wMonth = (WORD) ((INT)TimeFrom.wMonth + 1);
	}
	TimeTo.wDay = 1;
	TimeTo.wHour = 0;
	TimeTo.wMinute = 0;
	TimeTo.wSecond = 0;
}


// отчет по выбросам за день
if (report_type == 1){
	if (report_action == 1) {
		// формат времени
		SetPropChar(lpszPictureName, "Table", "TimeColumnTimeFormat", "HH ч - ");
		// видимость даты
		SetPropBOOL(lpszPictureName, "Table", "TimeColumnShowDate", 0);
		// устанавливаем видимость необходимых столбцов
		for (i = 0; i < 7; i++) {
			SetPropWord(lpszPictureName, "Table", "ValueColumnIndex", i);
			SetPropBOOL(lpszPictureName, "Table", "ValueColumnVisible", 1);
		}
	}

	// массив имен архивов
	lpszTagName[0] = "2203AZ/CO2_emis_hour.V";
	lpszTagName[1] = "2203AZ/CO_emis_hour.V";
	lpszTagName[2] = "2203AZ/NOx_emis_hour.V";
	lpszTagName[3] = "2203AZ/NO_emis_hour.V";
	lpszTagName[4] = "2203AZ/NO2_emis_hour.V";
	lpszTagName[5] = "2203AZ/SO2_emis_hour.V";
	lpszTagName[6] = "2203AZ/dust_emis_hour.V";

	// время простоя
	lpszTagTimeBreak = "2203AZ/TimeBreak_Hour.V";

	// название отчета
	lpszReportName = "2203AZ_EmissionsDay";
}


// отчет по выбросам за месяц
if (report_type == 2){
	if (report_action == 1) {
		// задаем настройки элемента Online Trend Control
		// видимость даты
		SetPropBOOL(lpszPictureName, "Table", "TimeColumnShowDate", 1);
		// формат даты
		SetPropChar(lpszPictureName, "Table", "TimeColumnDateFormat", "dd.MM");
		// формат времени
		SetPropChar(lpszPictureName, "Table", "TimeColumnTimeFormat", "-");
		// устанавливаем видимость необходимых столбцов
		for (i = 7; i < 14; i++) {
			SetPropWord(lpszPictureName, "Table", "ValueColumnIndex", i);
			SetPropBOOL(lpszPictureName, "Table", "ValueColumnVisible", 1);
		}
	}

	// массив имен архивов
	lpszTagName[0] = "2203AZ/CO2_emis_day.V";
	lpszTagName[1] = "2203AZ/CO_emis_day.V";
	lpszTagName[2] = "2203AZ/NOx_emis_day.V";
	lpszTagName[3] = "2203AZ/NO_emis_day.V";
	lpszTagName[4] = "2203AZ/NO2_emis_day.V";
	lpszTagName[5] = "2203AZ/SO2_emis_day.V";
	lpszTagName[6] = "2203AZ/dust_emis_day.V";

	// время простоя
	lpszTagTimeBreak = "2203AZ/TimeBreak_Day.V";

	// название отчета
	lpszReportName = "2203AZ_EmissionsMonth";
}


// отчет по выбросам за год
if (report_type == 4){
	if (report_action == 1) {
		// задаем настройки элемента Online Trend Control
		// видимость даты
		SetPropBOOL(lpszPictureName, "Table", "TimeColumnShowDate", 1);
		// формат даты
		SetPropChar(lpszPictureName, "Table", "TimeColumnDateFormat", "MM");
		// формат времени
		SetPropChar(lpszPictureName, "Table", "TimeColumnTimeFormat", "-");
		// устанавливаем видимость необходимых столбцов
		for (i = 14; i < 19; i++) {
			SetPropWord(lpszPictureName, "Table", "ValueColumnIndex", i);
			SetPropBOOL(lpszPictureName, "Table", "ValueColumnVisible", 1);
		}
	}

	// массив имен архивов
	lpszTagName[0] = "2203AZ/CO2_emis_month.V";
	lpszTagName[1] = "2203AZ/CO_emis_month.V";
	lpszTagName[2] = "2203AZ/NOx_emis_month.V";
	lpszTagName[3] = "2203AZ/NO_emis_month.V";
	lpszTagName[4] = "2203AZ/NO2_emis_month.V";
	lpszTagName[5] = "2203AZ/SO2_emis_month.V";
	lpszTagName[6] = "2203AZ/SO2_emis_month.V";

	// время простоя
	lpszTagTimeBreak = "2203AZ/TimeBreak_Hour.V";
}


// отчет по выбросам (общая часть)
if (report_type == 1 || report_type == 2 || report_type == 4) {

	// массив тегов суммарных выбросов из архива
	lpszTagEmisArchive[0] = "2203AZ_Report_CO2";
	lpszTagEmisArchive[1] = "2203AZ_Report_CO";
	lpszTagEmisArchive[2] = "2203AZ_Report_NOx";
	lpszTagEmisArchive[3] = "2203AZ_Report_NO";
	lpszTagEmisArchive[4] = "2203AZ_Report_NO2";
	lpszTagEmisArchive[5] = "2203AZ_Report_SO2";
	lpszTagEmisArchive[6] = "2203AZ_Report_Dust";

	// массив тегов выбросов за простой
	lpszTagEmisStop[0] = "2203AZ_Report_CO2_Stop";
	lpszTagEmisStop[1] = "2203AZ_Report_CO_Stop";
	lpszTagEmisStop[2] = "2203AZ_Report_NOx_Stop";
	lpszTagEmisStop[3] = "2203AZ_Report_NO_Stop";
	lpszTagEmisStop[4] = "2203AZ_Report_NO2_Stop";
	lpszTagEmisStop[5] = "2203AZ_Report_SO2_Stop";
	lpszTagEmisStop[6] = "2203AZ_Report_Dust_Stop";
	
	// массив тегов суммарных выбросов
	lpszTagEmisTotal[0] = "2203AZ_Report_CO2_Sum";
	lpszTagEmisTotal[1] = "2203AZ_Report_CO_Sum";
	lpszTagEmisTotal[2] = "2203AZ_Report_NOx_Sum";
	lpszTagEmisTotal[3] = "2203AZ_Report_NO_Sum";
	lpszTagEmisTotal[4] = "2203AZ_Report_NO2_Sum";
	lpszTagEmisTotal[5] = "2203AZ_Report_SO2_Sum";
	lpszTagEmisTotal[6] = "2203AZ_Report_Dust_Sum";
	
	// массив значений средних выбросов
	emisAvg[0] = GetTagFloat("2203AZ/CO2_emis_avg.V");
	emisAvg[1] = GetTagFloat("2203AZ/CO_emis_avg.V");
	emisAvg[2] = GetTagFloat("2203AZ/NOx_emis_avg.V");
	emisAvg[3] = GetTagFloat("2203AZ/NO_emis_avg.V");
	emisAvg[4] = GetTagFloat("2203AZ/NO2_emis_avg.V");
	emisAvg[5] = GetTagFloat("2203AZ/SO2_emis_avg.V");
	emisAvg[6] = GetTagFloat("2203AZ/dust_emis_avg.V");

	// обнулить итоговые поля
	for (i = 0; i < NumberOfData; i++) {
		SetTagDouble(lpszTagEmisArchive[i], -1);
		SetTagDouble(lpszTagEmisStop[i], -1);
		SetTagDouble(lpszTagEmisTotal[i], -1);
	}

	// собираем строки
	sprintf(date_begin, "%02d.%02d.%04d 00:00:00", TimeFrom.wDay, TimeFrom.wMonth, TimeFrom.wYear);
	sprintf(date_end, "%02d.%02d.%04d 00:00:00", TimeTo.wDay, TimeTo.wMonth, TimeTo.wYear);
	sprintf(date_range, "(%s - %s)", date_begin, date_end);

	SetTagChar("2203AZ_Report_BeginTime", date_begin);
	SetTagChar("2203AZ_Report_EndTime", date_end);
	SetTagChar("2203AZ_Report_TimeRange", date_range);

	// Online Table Control
	if (report_action == 1) {
		SetPropChar(lpszPictureName, "Table", "TimeColumnBeginTime", date_begin);
		SetPropChar(lpszPictureName, "Table", "TimeColumnEndTime", date_end);
		SetPropChar(lpszPictureName, "2203AZ_Report_TimeRange_Emissions", "Text", date_range);
	}

	// пробуем подключаться к Tag Logging
	fRet = TLGConnect(NULL, NULL);
	if (fRet == FALSE) {
		MessageBox(NULL, "Нет соединения с Tag Logging", "Ошибка", MB_ICONWARNING | MB_OK | MB_SYSTEMMODAL);
		goto end;
	}

	// считываем выбросы по каждому газу
	for (i = 0; i < NumberOfData; i++) {
		Number = 0;
		if (TLGGetArchivDataEx(lpszArchivName, lpszTagName[i], &TimeFrom, &TimeTo, &ADR, &Number, NULL, NULL) == TRUE) {
			if (ADR != NULL) {
				emisArchive[i] = 0;
				for (j = 0; j < Number; j++) emisArchive[i] += ADR[j].doValue;
			}
			TLGFreeMemory(ADR);
			SetTagDouble(lpszTagEmisArchive[i], emisArchive[i] / 1000);
		}
		else {
			MessageBox(NULL, "Нет данных", "Ошибка", MB_ICONWARNING | MB_OK);
			goto end;
		}
	}

	// считываем время простоя
	Number = 0;
	if (TLGGetArchivDataEx(lpszArchivName, lpszTagTimeBreak, &TimeFrom, &TimeTo, &ADR, &Number, NULL, NULL) == TRUE) {
		if (ADR != NULL) {
			timeBreak = 0;
			for (j = 0; j < Number; j++)  timeBreak += ADR[j].doValue;
		}
		TLGFreeMemory(ADR);
		SetTagDouble("2203AZ_Report_TimeBreak", timeBreak / 60);
	}
	else {
		MessageBox(NULL, "Нет данных", "Ошибка", MB_ICONWARNING | MB_OK);
		goto end;
	}

	// рассчитываем выбросы за простой и суммарные выбросы
	for (i = 0; i < NumberOfData; i++) {
		emisStop[i] = timeBreak * emisAvg[i] / 3600;
		emisTotal[i] = emisStop[i] + emisArchive[i];
		SetTagDouble(lpszTagEmisStop[i], emisStop[i] / 1000);
		SetTagDouble(lpszTagEmisTotal[i], emisTotal[i] / 1000);
	}

	// отключаемся от Tag Logging
	TLGDisconnect(NULL);


	// печатаем отчет
	if (report_action == 2) {
		RPTJobPreview(lpszReportName);
	}
}

// отчет по превышениям (общая часть)
if (report_type == 8 || report_type == 16){
	// массив полей для вывода отчета
	lpszExcess[0][0] = "2203AZ_Report_Excess_5_CO2";
	lpszExcess[1][0] = "2203AZ_Report_Excess_10_CO2";
	lpszExcess[2][0] = "2203AZ_Report_Excess_15_CO2";
	lpszExcess[3][0] = "2203AZ_Report_Excess_20_CO2";
	lpszExcess[4][0] = "2203AZ_Report_Excess_25_CO2";
	lpszExcess[5][0] = "2203AZ_Report_Excess_30_CO2";
	lpszExcess[6][0] = "2203AZ_Report_Excess_35_CO2";
	lpszExcess[7][0] = "2203AZ_Report_Excess_40_CO2";
	lpszExcess[8][0] = "2203AZ_Report_Excess_45_CO2";
	lpszExcess[9][0] = "2203AZ_Report_Excess_50_CO2";
	lpszExcess[0][1] = "2203AZ_Report_Excess_5_CO";
	lpszExcess[1][1] = "2203AZ_Report_Excess_10_CO";
	lpszExcess[2][1] = "2203AZ_Report_Excess_15_CO";
	lpszExcess[3][1] = "2203AZ_Report_Excess_20_CO";
	lpszExcess[4][1] = "2203AZ_Report_Excess_25_CO";
	lpszExcess[5][1] = "2203AZ_Report_Excess_30_CO";
	lpszExcess[6][1] = "2203AZ_Report_Excess_35_CO";
	lpszExcess[7][1] = "2203AZ_Report_Excess_40_CO";
	lpszExcess[8][1] = "2203AZ_Report_Excess_45_CO";
	lpszExcess[9][1] = "2203AZ_Report_Excess_50_CO";
	lpszExcess[0][2] = "2203AZ_Report_Excess_5_NOx";
	lpszExcess[1][2] = "2203AZ_Report_Excess_10_NOx";
	lpszExcess[2][2] = "2203AZ_Report_Excess_15_NOx";
	lpszExcess[3][2] = "2203AZ_Report_Excess_20_NOx";
	lpszExcess[4][2] = "2203AZ_Report_Excess_25_NOx";
	lpszExcess[5][2] = "2203AZ_Report_Excess_30_NOx";
	lpszExcess[6][2] = "2203AZ_Report_Excess_35_NOx";
	lpszExcess[7][2] = "2203AZ_Report_Excess_40_NOx";
	lpszExcess[8][2] = "2203AZ_Report_Excess_45_NOx";
	lpszExcess[9][2] = "2203AZ_Report_Excess_50_NOx";
	lpszExcess[0][3] = "2203AZ_Report_Excess_5_NO";
	lpszExcess[1][3] = "2203AZ_Report_Excess_10_NO";
	lpszExcess[2][3] = "2203AZ_Report_Excess_15_NO";
	lpszExcess[3][3] = "2203AZ_Report_Excess_20_NO";
	lpszExcess[4][3] = "2203AZ_Report_Excess_25_NO";
	lpszExcess[5][3] = "2203AZ_Report_Excess_30_NO";
	lpszExcess[6][3] = "2203AZ_Report_Excess_35_NO";
	lpszExcess[7][3] = "2203AZ_Report_Excess_40_NO";
	lpszExcess[8][3] = "2203AZ_Report_Excess_45_NO";
	lpszExcess[9][3] = "2203AZ_Report_Excess_50_NO";
	lpszExcess[0][4] = "2203AZ_Report_Excess_5_NO2";
	lpszExcess[1][4] = "2203AZ_Report_Excess_10_NO2";
	lpszExcess[2][4] = "2203AZ_Report_Excess_15_NO2";
	lpszExcess[3][4] = "2203AZ_Report_Excess_20_NO2";
	lpszExcess[4][4] = "2203AZ_Report_Excess_25_NO2";
	lpszExcess[5][4] = "2203AZ_Report_Excess_30_NO2";
	lpszExcess[6][4] = "2203AZ_Report_Excess_35_NO2";
	lpszExcess[7][4] = "2203AZ_Report_Excess_40_NO2";
	lpszExcess[8][4] = "2203AZ_Report_Excess_45_NO2";
	lpszExcess[9][4] = "2203AZ_Report_Excess_50_NO2";
	lpszExcess[0][5] = "2203AZ_Report_Excess_5_SO2";
	lpszExcess[1][5] = "2203AZ_Report_Excess_10_SO2";
	lpszExcess[2][5] = "2203AZ_Report_Excess_15_SO2";
	lpszExcess[3][5] = "2203AZ_Report_Excess_20_SO2";
	lpszExcess[4][5] = "2203AZ_Report_Excess_25_SO2";
	lpszExcess[5][5] = "2203AZ_Report_Excess_30_SO2";
	lpszExcess[6][5] = "2203AZ_Report_Excess_35_SO2";
	lpszExcess[7][5] = "2203AZ_Report_Excess_40_SO2";
	lpszExcess[8][5] = "2203AZ_Report_Excess_45_SO2";
	lpszExcess[9][5] = "2203AZ_Report_Excess_50_SO2";
	
	// массив полей для вывода суммы
	lpszExcessTotal[0] = "2203AZ_Report_Excess_Total_CO2";
	lpszExcessTotal[1] = "2203AZ_Report_Excess_Total_CO";
	lpszExcessTotal[2] = "2203AZ_Report_Excess_Total_NOx";
	lpszExcessTotal[3] = "2203AZ_Report_Excess_Total_NO";
	lpszExcessTotal[4] = "2203AZ_Report_Excess_Total_NO2";
	lpszExcessTotal[5] = "2203AZ_Report_Excess_Total_SO2";

	// обнулим поля
	for (j = 0; j < 6; j++) {
		for (i = 0; i < 10; i++) SetPropDouble(lpszPictureName, lpszExcess[i][j], "OutputValue", 0);
		SetPropDouble(lpszPictureName, lpszExcessTotal[j], "OutputValue", 0);
	}

	// собираем строки
	sprintf(date_begin, "%02d.%02d.%04d 00:00:00", TimeFrom.wDay, TimeFrom.wMonth, TimeFrom.wYear);
	sprintf(date_end, "%02d.%02d.%04d 00:00:00", TimeTo.wDay, TimeTo.wMonth, TimeTo.wYear);
	sprintf(date_range, "(%s - %s)", date_begin, date_end);

	SetPropChar(lpszPictureName, "2203AZ_Report_TimeRange_Excess", "Text", date_range);

	//массив имен архивов
	lpszTagName[0] = "2203AZ/CO2_emis_current.V";
	lpszTagName[1] = "2203AZ/CO_emis_current.V";
	lpszTagName[2] = "2203AZ/NOx_emis_current.V";
	lpszTagName[3] = "2203AZ/NO_emis_current.V";
	lpszTagName[4] = "2203AZ/NO2_emis_current.V";
	lpszTagName[5] = "2203AZ/SO2_emis_current.V";

	// массив максимальных значений
	emisMax[0] = GetTagFloat("2203AZ/CO2_emis_max.V");
	emisMax[1] = GetTagFloat("2203AZ/CO_emis_max.V");
	emisMax[2] = GetTagFloat("2203AZ/NOx_emis_max.V");
	emisMax[3] = GetTagFloat("2203AZ/NO_emis_max.V");
	emisMax[4] = GetTagFloat("2203AZ/NO2_emis_max.V");
	emisMax[5] = GetTagFloat("2203AZ/SO2_emis_max.V");

	
	// пробуем подключаться к Tag Logging
	fRet = TLGConnect(NULL, NULL);
	if (fRet == FALSE) {
		MessageBox(NULL, "Нет соединения с Tag Logging", "Ошибка", MB_ICONWARNING | MB_OK | MB_SYSTEMMODAL);
		goto end;
	}
	
	// подсчитываем проценты превышений по каждому газу
	for (j = 0; j < 6; j++) {
		Number = 0;
		if (TLGGetArchivDataEx(lpszArchivName, lpszTagName[j], &TimeFrom, &TimeTo, &ADR, &Number, NULL, NULL) == TRUE) {
			if (ADR != NULL) {
				// обнуляем значения
				for (i = 0; i < 10; i ++) excess[i][j] = 0;
				// проходим по массиву значений
				for (i = 0; i < Number; i++){
					percent = (ADR[i].doValue - emisMax[j]) / emisMax[j] * 100;
					if (percent < 5) continue;
					else if (percent >=5 && percent < 10) excess[0][j] += 1;
					else if (percent >= 10 && percent < 15) excess[1][j] += 1;
					else if (percent >= 15 && percent < 20) excess[2][j] += 1;
					else if (percent >= 20 && percent < 25) excess[3][j] += 1;
					else if (percent >= 25 && percent < 30) excess[4][j] += 1;
					else if (percent >= 30 && percent < 35) excess[5][j] += 1;
					else if (percent >= 35 && percent < 40) excess[6][j] += 1;
					else if (percent >= 40 && percent < 45) excess[7][j] += 1;
					else if (percent >= 45 && percent < 50) excess[8][j] += 1;
					else excess[9][j] += 1;
				}
				emisTotal[j] = 0;
				for (i = 0; i < 10; i++) {
					// вычисляем проценты
					excess[i][j] = excess[i][j] / Number * 100;
					SetPropDouble(lpszPictureName, lpszExcess[i][j], "OutputValue", excess[i][j]);
					// вычисляем сумму
					excessTotal[j] += excess[i][j];
				}
				SetPropDouble(lpszPictureName, lpszExcessTotal[j], "OutputValue", excessTotal[j]);
			}
			TLGFreeMemory(ADR);
		}
		else {
			MessageBox(NULL, "Нет данных", "Ошибка", MB_ICONWARNING | MB_OK);
			goto end;
		}
	}

	// отключаемся от Tag Logging
	TLGDisconnect(NULL);
}


//метка завершения
end:

// активируем элементы
SetPropChar(lpszPictureName, "Report_Build", "Text", "OK");
SetPropBOOL(lpszPictureName, "Report_Build", "Operation", 1);
SetPropBOOL(lpszPictureName, "2203AZ_Report_Type", "Operation", 1);
SetPropBOOL(lpszPictureName, "2203AZ_Report_Action", "Operation", 1);
SetPropBOOL(lpszPictureName, "2203AZ_Report_Day", "Operation", 1);
SetPropBOOL(lpszPictureName, "2203AZ_Report_Month", "Operation", 1);
SetPropBOOL(lpszPictureName, "2203AZ_Report_Year", "Operation", 1);
}