コード例 #1
8
TSTRING OverwriteDlg::_GetNumberFormat(UINT64 ui64Num) {

  TSTRING r;

  sprintf(r, _T("%I64d"), ui64Num);

  int iAlloc = GetNumberFormat(LOCALE_SYSTEM_DEFAULT,
                               0UL,
                               r.c_str(),
                               NULL,
                               NULL,
                               0);

  if (0 < iAlloc) {

    TCHAR *szBuf = new TCHAR[iAlloc];

    if (NULL != szBuf) {

      RtlZeroMemory(szBuf, iAlloc * sizeof(TCHAR));

      NUMBERFMT nf          = {0};
      TSTRING tsDecSep  = _GetLocaleInfoString(LOCALE_SMONDECIMALSEP);
      TSTRING tsThouSep = _GetLocaleInfoString(LOCALE_STHOUSAND);

      nf.LeadingZero   = _GetLocaleInfoNumeric(LOCALE_ILZERO);
      nf.Grouping      = _GetLocaleInfoNumeric(LOCALE_SGROUPING);
      nf.lpDecimalSep  = const_cast<TCHAR *>(tsDecSep.c_str());
      nf.lpThousandSep = const_cast<TCHAR *>(tsThouSep.c_str());
      nf.NegativeOrder = _GetLocaleInfoNumeric(LOCALE_INEGNUMBER);
      nf.NumDigits     = 0U;

      if (0 != GetNumberFormat(LOCALE_SYSTEM_DEFAULT,
                               0UL,
                               r.c_str(),
                               &nf,
                               szBuf,
                               iAlloc))
      {

        r = szBuf;

      }

      delete szBuf;
    }

  }

  return r;
}
コード例 #2
0
ファイル: Statement.cpp プロジェクト: Rudeman/achat
 Handle<Value> Statement::GetFieldValueByIndex(const Arguments& args)
 {
	 Statement* pStatement = ObjectWrap::Unwrap<Statement>(args.This());
	 HandleScope scope;
	 int index = args[0]->Int32Value();
	 Sqlite3_XX::VARIANT var = pStatement->pRecord->GetFieldValue(index);
	 if (var.vt == Sqlite3_XX::VT_BSTR)
	 {
		 TSTRING value = var.bstrVal;
#ifdef OS_WIN32
		 return scope.Close(String::New(encodeConv::CodingConv::Unicode2Utf8(value.c_str()).c_str()));

#elif defined OS_LINUX
		  return scope.Close(String::New(value.c_str()));
#endif

	 }
	 else if (var.vt == Sqlite3_XX::VT_I4)
	 {
		 return scope.Close(Integer::New(var.intVal));
	 }
	 else if (var.vt == Sqlite3_XX::VT_R8)
	 {
		  return scope.Close(Number::New(var.dblVal));
	 }
	return Undefined();
	
 }
コード例 #3
0
void cUnixFSServices::ReadDir(const TSTRING& strFilename, std::vector<TSTRING>& v, bool bFullPaths) const
{
#else
void cUnixFSServices::ReadDir(const TSTRING& strFilenameC, std::vector<TSTRING>& v, bool bFullPaths) const
{
    TSTRING strFilename = cDevicePath::AsNative(strFilenameC);
#endif

    //Get all the filenames
    DIR* dp = 0;

#if defined(O_DIRECTORY) && defined(O_NOATIME)
    //dfd will be autoclosed by closedir(), should not be explicitly closed.
    int dfd = open(strFilename.c_str(), O_RDONLY | O_DIRECTORY | O_NOATIME);
    if (dfd > 0)
        dp = fdopendir(dfd);
#else
    dp = opendir(strFilename.c_str());
#endif

    if (dp == NULL)
    {
        throw eFSServicesGeneric(strFilename, iFSServices::GetInstance()->GetErrString());
        return;
    }

    struct dirent* d;

    while ((d = readdir(dp)) != NULL)
    {
        if ((strcmp(d->d_name, _T(".")) != 0) && (strcmp(d->d_name, _T("..")) != 0))
        {
            if (bFullPaths)
            {
                //Create the full pathname
                TSTRING strNewName = strFilename;

                // get full path of dir entry
                util_TrailingSep(strNewName, true);
                strNewName += d->d_name;

                // save full path name
                v.push_back(strNewName);
            }
            else
                v.push_back(d->d_name);
        }
    }

    //Close the directory
    closedir(dp);
}
コード例 #4
0
ファイル: oldhelp.cpp プロジェクト: thenfour/_tWinMain
bool CHelpDB::NewItem(CTSTRING& _sAlias, CTSTRING& sText, CTSTRING& sCreator)
{
    MSXML::IXMLDOMElementPtr El;
    bool r = false;
    if(m_doc == 0) return false;
    TSTRING sAlias;

    {
        TCHAR* tsz = _tcsdup(_sAlias.c_str());
        _tcsupr(tsz);
        sAlias = tsz;
        SAFE_FREE(tsz);
    }

    // Just determine if it exists.
    if(GetItemElement(sAlias, El, false))
    {
        // it already exists; fail.
        sprintf(m_err, _T("%s already exists.  If you want to change the existing entry, use !msgchange."), sAlias.c_str());
        g_pLog->msg(_T("%s"), m_err.c_str());
    }
    else
    {
        // doesn't already exist... we're golden like the shower.  This time
        // just call GetItemElement() with bCreate set to true.
        if(!GetItemElement(sAlias, El, true))
        {
            sprintf(m_err, _T("%s could not be added."), sAlias.c_str());
            g_pLog->msg(_T("%s"), m_err.c_str());
        }
        else
        {
            El->setAttribute(TAG_ALIAS, sAlias.c_str());
            El->setAttribute(TAG_CREATOR, sCreator.c_str());
            El->setAttribute(TAG_TEXT, sText.c_str());
            El->setAttribute(TAG_USAGE, _T("0"));
            SYSTEMTIME st;
            TSTRING sTime;
            GetLocalTime(&st);
            Bin2Str(sTime, (BYTE*)&st, sizeof(st));
            El->setAttribute(TAG_TIME, sTime.c_str());

            g_pLog->msg(_T("New db item: %s = %s"), _sAlias.c_str(), sText.c_str());

            r = true;
        }
    }

    return r;
}
コード例 #5
0
void CSoundManager::LoadSound( TSTRING szFilename, TSTRING szReference, bool isMusic )
{
	CSGD_XAudio2* pXA = CSGD_XAudio2::GetInstance();
	int newID;
	if( isMusic )
		newID = pXA->MusicLoadSong(szFilename.c_str());
	else
		newID = pXA->SFXLoadSound(szFilename.c_str());

	SoundID newSoundID;
	newSoundID.first = szReference;
	newSoundID.second = newID;

	m_vSoundIDs.push_back(newSoundID);
}
コード例 #6
0
bool OverwriteDlg::_SetStaticText(Window &Wnd, CTSTRING &tsFileName) {

  bool r = false;
  FILESIZE fs;

  if (FileGetSize(tsFileName, fs)) {

    FILETIMES ft;

    if (FileGetTime(tsFileName, ft)) {

     /*
      * Set the text of the static control as follows:
      *
      * [size in bytes] [formatted size]
      * [created date]
      * [modified date]
      */
      TSTRING tsTemp;
      TSTRING tsFormatBytes = _GetNumberFormat(fs.ui64Bytes);                    

      sprintf(tsTemp, _T("%s Bytes (%s)\nCreated: %s\nModified: %s"),
              tsFormatBytes.c_str(), fs.tsStrFmt.c_str(),
              ft.tsLongCreated.c_str(), ft.tsLongModified.c_str());

      Wnd.SetWindowText(tsTemp);
      r = true;

    }

  }

  return r;
}
コード例 #7
0
///////////////////////////////////////////////////////////////////////////////
// LookupArgInfo
///////////////////////////////////////////////////////////////////////////////
bool cCmdLineParser::LookupArgInfo(int argId, TSTRING& arg, TSTRING& alias) const
{
    arg     = _T("");
    alias   = _T("");

    cHashTableIter<TSTRING, cArgInfo> iter(mArgTable);
    for(iter.SeekBegin(); ! iter.Done(); iter.Next())
    {
        if(iter.Val().mId == argId)
        {
            TSTRING str = iter.Key();
            if((str.length() > 0) && (str[0] == _T('-')))
            {
                // this is the alias!
                alias = (str.c_str() + 1);
            }
            else
            {
                // this is the arg...
                arg = str;
            }
        }
    }
    return ((! arg.empty()) || (! alias.empty()));
}
コード例 #8
0
void CameraControlsDlg::_DoZeroAccumulator(void) {

  TSTRING tsMsg;

  sprintf(tsMsg, _T("Are you sure you want")
          _T(" to zero the step accumulator and")
          _T(" global frame count?\n\n")
          _T("Frame count is currently: %d\n"),
          *m_pdwFrameCount);

  if (IDYES == MessageBox(m_hWnd, tsMsg.c_str(),
                          _T("FURR - Confirm Accumulator Reset"),
                          MB_YESNO | MB_ICONQUESTION))
  {

    if (!m_AMSComm.Camera_ResetAccumulator()) {

      _ThrowAMSError();

    } else {

      *m_pdwFrameCount = 0UL;
      m_pParent->Output(FURR_OT_INFORMATION, _T("CameraControls:")
                        _T("Set step accumulator and frame count to zero"));

    }

  }

}
コード例 #9
0
ファイル: SLog.cpp プロジェクト: KennGuilstorf/SPerfTest
	/// <summary>
	/// <para name='Name'>SLog::getDateTimeString</para>
	/// <para name='Purpose'>Return a formatted date time string</para>
	/// </summary>
	/// <param name='logFormat'>indicate whether to return the date time string in log format or decoration format</param>
	/// <returns>a formatted date/time string</returns>
	/// <remarks>
	/// <para name='Notes'></para>
	/// <para name='Author'>Kenn Guilstorf</para>
	/// <para name='LastModified'>2015-10-26</para>
	/// </remarks>
	TSTRING SLog::getDateTimeString(bool logFormat)
	{
		TSTRING retValue;
		TSTRING strFormat;
		TCHAR* chBuffer = new TCHAR[50];
		SYSTEMTIME st;

		if (logFormat)
		{
			strFormat = TSTRING(_T("%04d-%02d-%02d %02d:%02d:%02d.%03d | "));
		}
		else
		{
			strFormat = TSTRING(_T(".%04d%02d%02d.%02d%02d%02d%03d"));
		}

		GetLocalTime(&st);

		SPRINTF(chBuffer,
			50,
			strFormat.c_str(),
			(int)st.wYear, 
			(int)st.wMonth, 
			(int)st.wDay, 
			(int)st.wHour, 
			(int)st.wMinute, 
			(int)st.wSecond, 
			(int)st.wMilliseconds);
		
		retValue = TSTRING(chBuffer);

		return retValue;
	}
コード例 #10
0
////////////////////////////////////////////////////////////////////////
// Function name    : cUnixFSServices::Rename
// Description      : Rename a file.  Overwrites newname if it exists.and overwrite is true
//
// Returns          : false if failure, true on success
bool cUnixFSServices::Rename(const TSTRING& strOldName, const TSTRING& strNewName, bool overwrite) const
{
#ifdef _UNICODE
#    error UNICODE Rename not implemented
#endif

    // delete new file if overwriting
    if (overwrite)
        if (access(strNewName.c_str(), F_OK) == 0 && remove(strNewName.c_str()) != 0)
            return false;

    if (rename(strOldName.c_str(), strNewName.c_str()) == 0)
        return true;

    // Note: errno will be set
    return false;
}
コード例 #11
0
ファイル: oldhelp.cpp プロジェクト: thenfour/_tWinMain
bool CHelpDB::GetItemElement(CTSTRING& _sAlias, MSXML::IXMLDOMElementPtr& Out, bool bCreate)
{
    bool r = false;
    TSTRING sXPath;
    MSXML::IXMLDOMNodePtr Node;
    TSTRING sAlias;

    {
        TCHAR* tsz = _tcsdup(_sAlias.c_str());
        _tcsupr(tsz);
        sAlias = tsz;
        SAFE_FREE(tsz);
    }

    // this will look something like MSG[@ALIAS="hithere"]
    sprintf(sXPath, TAG_MSG _T("[@") TAG_ALIAS _T("=\"%s\"]"), sAlias.c_str());

    try
    {
        Node = m_root->selectSingleNode(_bstr_t(sXPath.c_str()));

        if((Node == NULL) && (bCreate == true))
        {
            MSXML::IXMLDOMElementPtr NewEl;
            MSXML::IXMLDOMNodePtr NewNode;

            NewEl = m_doc->createElement("MSG");
            NewEl.QueryInterface(__uuidof(MSXML::IXMLDOMNode), &NewNode);
            Node = m_root->appendChild(NewNode);
        }

        if(Node != NULL)
        {
            Node.QueryInterface(__uuidof(MSXML::IXMLDOMElement), &Out);
            r = true;
        }
    }
    catch(_com_error& e)
    {
        sprintf(m_err, _T("COM Error: %08x"), e.Error());
        g_pLog->msg(_T("CHelpDB::GetItemElement(%s)"), _sAlias.c_str());
    }

    return r;
}
コード例 #12
0
bool util_FileExists(const TSTRING& fileName)
{
#if IS_UNIX
    // for unix we may be able to use the same logic as above, but
    // it is too close to 2.2.1 release to make that change w/o testing.
    // I know the above works for windows.
    return _taccess(fileName.c_str(), F_OK) == 0;
#endif
}
コード例 #13
0
ファイル: Statement.cpp プロジェクト: Rudeman/achat
Handle<Value> Statement::GetFieldName(const Arguments& args)
 {
	 int index = args[0]->Int32Value();
	 HandleScope scope;
	 Statement* pStatement = ObjectWrap::Unwrap<Statement>(args.This());
	 TSTRING name = pStatement->pRecord->GetFieldName(index);

#ifdef OS_WIN32
	 return scope.Close(String::New(encodeConv::CodingConv::Unicode2Utf8(name.c_str()).c_str()));

	 
#elif defined OS_LINUX
	  return scope.Close(String::New(name.c_str()));

#endif
	  return Undefined();

 }
コード例 #14
0
static void PrintIter(const iFCOIter* pIter, cDebug& d)
{
    TSTRING str;
    for(; ! pIter->Done(); pIter->Next())
    {
        str += pIter->FCO()->GetName().AsString().c_str();
        str += _T(" ");
    }
    d.TraceDebug(_T("%s\n"), str.c_str());
}
コード例 #15
0
void cPipedMailMessage::SendString(const TSTRING& s)
{
    if (_ftprintf(mpFile, "%s", s.c_str()) < 0)
    {
        TOSTRINGSTREAM estr;
        estr << TSS_GetString(cTripwire, tripwire::STR_ERR2_MAIL_MESSAGE_COMMAND) << mstrSendMailExePath;

        throw eMailPipedOpen(estr.str());
    }
}
コード例 #16
0
ファイル: SLog.cpp プロジェクト: KennGuilstorf/SPerfTest
	/// <summary>
	/// <para name='Name'>SLog::openLog</para>
	/// <para name='Purpose'>Open a log for output</para>
	/// </summary>
	/// <param name='szFullPathToLog'>the full path to the log file to open</param>
	/// <param name='makeUnique'>Whether to append a date/time stamp to the file name</param>
	/// <returns>S_OK if successful, failure if it failed</returns>
	/// <remarks>
	/// <para name='Notes'></para>
	/// <para name='Author'>Kenn Guilstorf</para>
	/// <para name='LastModified'>2015-10-26</para>
	/// </remarks>
	HRESULT SLog::openLog(TSTRING szFullPathToLog, bool makeUnique)
	{
		HRESULT hrRetVal = S_OK;
		TSTRING szFullLogPath = TSTRING();

		// If we're trying to open when a log is already open...
		// Let's flush and close the main OSTREAM first...
		if (NULL != m_pO)
		{
			m_pO->flush();
			delete m_pO;
			m_pO = NULL;
		}

		// Now, close the file stream...
		if (NULL != m_log)
		{
			if (m_log->is_open())
			{
				m_log->flush();
				m_log->close();
				delete m_log;
				m_log = NULL;
			}
		}

		// Split the path into path, name and ext
		hrRetVal = splitFullPath(szFullPathToLog);
		if (hrRetVal == ERROR_BAD_ARGUMENTS)
			goto EXIT;

		// Do we want to add date/time to the file?
		if (makeUnique)
			m_szLogFileName->append(getDateTimeString(false));

		szFullLogPath.append(m_szLogFilePath->c_str());
		szFullLogPath.append(m_szLogFileName->c_str());
		szFullLogPath.append(m_szLogFileExt->c_str());

		// Enter our critical section
		EnterCriticalSection(&m_CriticalSection);

		// Open our file stream
		m_log = new TOFSTREAM(szFullLogPath.c_str(),
			TOFSTREAM::app | TOFSTREAM::out);
		
		// Open a new output stream
		m_pO = new TOSTREAM(m_log->rdbuf());

		// Leave our critical section
		LeaveCriticalSection(&m_CriticalSection);

	EXIT:
		return hrRetVal;
	}
コード例 #17
0
///////////////////////////////////////////////////////////////////////////////
// OpenConfigFile -- opens the config file, either from a known location or
//      from the location specified on the command line. Returns false if it fails.
//      cfgFileID is the ID of the config file switch
//      TODO -- should this guy spit the error to cerr or fill up an error bucket?
/////////////////////////////////////////////////////////////////////////////////
void cTWUtil::OpenConfigFile(
    cConfigFile& cf, cCmdLineParser& cmdLine, int cfgFileID, cErrorBucket& errorBucket, TSTRING& configFileOut)
{

    configFileOut = GetCfgFilePath(cmdLine, cfgFileID);

    // ok, now let's load it!
    TSTRING configText;
    cTWUtil::ReadConfigText(configFileOut.c_str(), configText);
    cf.ReadString(configText);
}
コード例 #18
0
///////////////////////////////////////////////////////////////////////////////
// Function name    : util_FileIsExecutable
// Description      : file ( or file a link points to ) must be a regular
//                    file and executable by someone
//
// Return type      : bool
// Argument         : const TSTRING& strFile
///////////////////////////////////////////////////////////////////////////////
bool util_FileIsExecutable(const TSTRING& strFile)
{
    if (strFile.empty())
        return false;

    struct stat s;
    if (stat(strFile.c_str(), &s) < 0) // this call handles links
        return false;

    return (S_ISREG(s.st_mode) && (s.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))); // can someone execute it?
}
コード例 #19
0
///////////////////////////////////////////////////////////////////////////////
// OpenKeyFile
///////////////////////////////////////////////////////////////////////////////
void cTWUtil::OpenKeyFile(cKeyFile& keyFile, TSTRING fileName)
{
    // first, make sure the file exists...
    cFileUtil::TestFileExists(fileName);

    iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE,
                                       _T("%s%s\n"),
                                       TSS_GetString(cTW, tw::STR_OPEN_KEYFILE).c_str(),
                                       cDisplayEncoder::EncodeInline(fileName).c_str());

    keyFile.ReadFile(fileName.c_str());
}
コード例 #20
0
ファイル: Statement.cpp プロジェクト: Rudeman/achat
 Handle<Value> Statement::GetFieldValueByName(const Arguments& args)
 {
	  Statement* pStatement = ObjectWrap::Unwrap<Statement>(args.This());
	 HandleScope scope;
	 String::Utf8Value field_name(args[0]);
	// const char* pfield_name = ToCString(field_name);
	 TSTRING name;
#ifdef OS_WIN32

	 name = encodeConv::CodingConv::s2ws(ToCString(field_name));
#elif defined OS_LINUX
	 name = ToCString(field_name);
#endif
	 Sqlite3_XX::VARIANT var = pStatement->pRecord->GetFieldValue(name.c_str());
	 Local<Object> obj = Object::New();
	 if (var.vt == Sqlite3_XX::VT_BSTR)
	 {
		 TSTRING value = var.bstrVal;
#ifdef OS_WIN32
		 return scope.Close(String::New(encodeConv::CodingConv::Unicode2Utf8(value.c_str()).c_str()));

#elif defined OS_LINUX
		 return scope.Close(String::New(value.c_str()));
#endif

	 }
	 else if (var.vt == Sqlite3_XX::VT_I4)
	 {
		 return scope.Close(Integer::New(var.intVal));
	 }
	 else if (var.vt == Sqlite3_XX::VT_R8)
	 {
		 return scope.Close(Number::New(var.dblVal));
	 }
	 return Undefined();
	
 }
コード例 #21
0
void cTextDBViewer::PrintDB( cFCODatabaseFile& rd, const TSTRING& strFilename )
{
    TOSTREAM* pOut;
    TOFSTREAM fileOut;
    bool fIsFile = false;

    if( strFilename == _T("-") )
    {
        pOut = &TCOUT;
    }
    else
    {
        //Gonna have to insert a lame hack here, since ostr.open DEMANDS a const char*!!
        fileOut.open( strFilename.c_str() );

        if( fileOut.is_open() )
        {
            pOut = &fileOut;
            fIsFile = true;
        }
        else
        {
            ASSERT( false );
            throw eArchiveOpen( strFilename, iFSServices::GetInstance()->GetErrString() );
        }
    }

    InitOStream( pOut );
    
    //
    // output header, just like it sez....
    //
    OutputDatabaseHeader( rd.GetHeader(), pOut );

    OutputObjectSummary( rd, pOut, DETAILS_MARGIN );

    OutputObjectDetail( rd, pOut );

    
    // we're done
    (*pOut) << g_sz79Dashes << endl;
    (*pOut) << TSS_GetString( cTW, tw::STR_END_OF_DB ) << endl << endl;
    (*pOut) << TSS_GetString( cTW, tw::STR_COPYRIGHT ) << endl;    

    if( fIsFile )
        static_cast<TOFSTREAM*>(pOut)->close();

    return;
}
コード例 #22
0
// sGenre can be either short or long name
cGenreInfoVec::const_iterator cGenreInfoVec::find(const TSTRING& sGenre) const
{
    const_iterator i;
    for (i = begin(); i != end(); ++i)
    {
        ASSERT((*i)->m_ID != cGenre::GENRE_INVALID);

        //
        // compare against long and short name
        //
        if (_tcsicmp(sGenre.c_str(), (*i)->m_sLongName.c_str()) == 0 ||
            _tcsicmp(sGenre.c_str(), (*i)->m_sShortName.c_str()) == 0)
            break;
    }

    return (i);
}
コード例 #23
0
void cFSDataSourceIter::GetChildrenNames( const TSTRING& strParentName, std::vector<TSTRING>& vChildrenNames )
{
    try
    {
        iFSServices::GetInstance()->ReadDir( strParentName, vChildrenNames, false );
    }
    catch( eFSServices& e )
    {
        cDebug d("cFSDataSourceIter::GeneratePeers");
        d.TraceError("**** ReadDir failed for %s\n", strParentName.c_str() );

        if( mpErrorBucket )
        {
            eFSDataSourceIterReadDir eReadDir(e.GetMsg(), eError::NON_FATAL);
            mpErrorBucket->AddError( eReadDir );
        }
    }
}
コード例 #24
0
// method for getting a list of manipulators
// returns number of files matched
int cFileManipulator::LoadFiles(std::list<cFileManipulator>& ret, TSTRING mask)
{
    ret.clear();

    // TODO: we need to be able to deal with masks for the NT version.
    //  Right now *.* will not work in NT.  We should not get a '*' for unix.

    try
    {
        ret.push_back(cFileManipulator(mask.c_str()));
    }
    catch (eError&)
    {
        // file does not exist
        return 0;
    }

    return 1;
}
コード例 #25
0
ファイル: oldhelp.cpp プロジェクト: thenfour/_tWinMain
bool CHelpDB::ElementToStruct(CHelpMessage& info, MSXML::IXMLDOMElementPtr& El, bool bIncUsage)
{
    bool r = false;

    try
    {
        _variant_t vAlias = El->getAttribute(TAG_ALIAS);
        _variant_t vCreator = El->getAttribute(TAG_CREATOR);
        _variant_t vText = El->getAttribute(TAG_TEXT);
        _variant_t vCreated = El->getAttribute(TAG_TIME);
        _variant_t vUsage = El->getAttribute(TAG_USAGE);

        HW2T(info.Alias, vAlias.bstrVal);
        HW2T(info.Creator, vCreator.bstrVal);
        HW2T(info.Text, vText.bstrVal);

        TSTRING sTemp;

        HW2T(sTemp, vCreated.bstrVal);
        Str2Bin(sTemp, (PBYTE)&info.Created, sizeof(info.Created));

        HW2T(sTemp, vUsage.bstrVal);
        info.nUsage = _tcstoul(sTemp.c_str(), 0, 10);

        if(bIncUsage)
        {
            TCHAR tsz[500];
            info.nUsage++;
            _ultot(info.nUsage, tsz, 10);
            El->setAttribute(_bstr_t(TAG_USAGE), _variant_t(tsz));
        }

        r = true;
    }
    catch(_com_error& e)
    {
        sprintf(m_err, _T("COM Error: %08x"), e.Error(), (TCHAR*)e.Description());
        g_pLog->msg(_T("CHelpDB::ElementToStruct ERROR"));
    }

    return r;
}
コード例 #26
0
void OverwriteDlg::_DisplayFileInfo(void) {

  TSTRING tsTitle;
  TSTRING tsShortFile = GetFileFromPath(m_tsSrc);

 /*
  * Truncate file if necessary
  */
  tsShortFile = FileGetCompactName(tsShortFile, OD_MAXCURFILE);

  sprintf(tsTitle, _T("The file '%s' already exists in the")
          _T(" destination directory. Would you like to ")
          _T("replace this file:"), tsShortFile.c_str());

  m_sTitle.SetWindowText(tsTitle);

  SHFILEINFO sfi = {0};

  SHGetFileInfo(m_tsSrc.c_str(),
                0,
                &sfi,
                sizeof(sfi),
                SHGFI_ATTRIBUTES | SHGFI_LARGEICON | SHGFI_ICON);

  m_icoSrc.SendMsg(STM_SETICON, reinterpret_cast<WPARAM>(sfi.hIcon), 0);

  _SetStaticText(m_sSrc, m_tsSrc);

  RtlFillMemory(&sfi, sizeof(sfi), 0x00);

  SHGetFileInfo(m_tsDest.c_str(),
                0,
                &sfi,
                sizeof(sfi),
                SHGFI_ATTRIBUTES | SHGFI_LARGEICON | SHGFI_ICON);

  m_icoDest.SendMsg(STM_SETICON, reinterpret_cast<WPARAM>(sfi.hIcon), 0);

  _SetStaticText(m_sDest, m_tsDest);

}
コード例 #27
0
ファイル: oldhelp.cpp プロジェクト: thenfour/_tWinMain
bool CHelpDB::_FormatXML()
{
    bool r = false;

    TSTRING strIntermediate;
    BSTR strNewXML = 0;

    // get the XML code from the DOM
    try
    {
        {
            _bstr_t strOriginalXML;
            m_doc->replaceChild(m_root, m_doc->documentElement);
            strOriginalXML = m_doc->xml;
            strIntermediate = strOriginalXML;
        }

        HStrReplace(strIntermediate, _T("><"), _T(">\r\n<"));

        strNewXML = SysAllocString(strIntermediate.c_str());

        if(strNewXML)
        {
            //' load back into the DOM
            if(VARIANT_TRUE == m_doc->loadXML(strNewXML))
            {
                r = true;
            }

            SysFreeString(strNewXML);
            strNewXML = 0;
        }
    }
    catch(_com_error& e)
    {
        sprintf(m_err, _T("0x%08x"), e.Error());
        g_pLog->msg(_T("CHelpDB::_FormatXML COM ERROR"));
    }

    return r;
}
コード例 #28
0
///////////////////////////////////////////////////////////////////////////////
// SeekTo -- seeks to the named noun; this takes care of interpriting special 
//      nouns. If the seek fails, then Done() is true and false is returned.
//      If noun is a special character, then it is altered to what it mapped to.
///////////////////////////////////////////////////////////////////////////////
static bool SeekTo(cDbDataSourceIter* pIter, TSTRING& noun )
{
    if( noun[0] == _T('*') )
    {
        // interprite the rest of the string as a number index to seek to...
        int index = _ttoi( &noun[1] );
        if( index < 0 )
            return false;
        pIter->SeekBegin();
        for( int i=0; ((i < index) && (! pIter->Done())); i++, pIter->Next() )
        {

        }
        if( pIter->Done() )
            return false;
        noun = pIter->GetShortName();
        return true;
    }
    else
        return ( pIter->SeekTo( noun.c_str() ) );
}
コード例 #29
0
// Change the encryption on a file.
// If pNewKey is NULL, then encryption on the file will be removed.
// If pOldKey is NULL and the file is currently encrypted, then the
// function will throw eFileManip;
// If pOldKey is not NULL and the file is encrypted, then the fuction
// will throw eFileManip;
// If pOldKey is NULL and pNewKey is NULL and the file is not
// currently encrypted, the function will not do anything and will just
// return.
// Returns on successful encryption change.
void cFileManipulator::ChangeEncryption(const cElGamalSigPublicKey*  pOldKey,
                                        const cElGamalSigPrivateKey* pNewKey,
                                        bool                         backup)
{
    ASSERT(mbInit);
    if (!mbInit)
    {
        Init();
    }

    // check the pOldKey matches the current encryption state
    if (mFileHeader.GetEncoding() != cFileHeader::ASYM_ENCRYPTION)
    {
        if (pOldKey != NULL)
            throw eFileManipNotEncrypted(mFileName);
        if (pNewKey == NULL)
            return; // NOOP
    }
    else if (pOldKey == NULL)
        throw eFileManipMissingKey();

    if (!cFileUtil::FileWritable(mFileName))
        throw eFileManipNotWritable(mFileName);

    if (mFileHeader.GetID() == cFCODatabaseFile::GetFileHeaderID())
    {
        cFCODatabaseFile db;
        bool             encrypted;

        cTWUtil::ReadDatabase(mFileName.c_str(), db, pOldKey, encrypted);
        if (backup)
        {
            TSTRING backname = mFileName + iFSServices::GetInstance()->GetStandardBackupExtension();
            iFSServices::GetInstance()->Rename(mFileName.c_str(), backname.c_str());
        }

        cTWUtil::WriteDatabase(mFileName.c_str(), db, pNewKey != NULL, pNewKey);
        return;
    }
    else if (mFileHeader.GetID() == cFCOReport::GetFileHeaderID())
    {
        cFCOReport       rep;
        cFCOReportHeader reph;
        bool             encrypted;
        cTWUtil::ReadReport(mFileName.c_str(), reph, rep, pOldKey, false, encrypted);
        if (backup)
        {
            TSTRING backname = mFileName + iFSServices::GetInstance()->GetStandardBackupExtension();
            iFSServices::GetInstance()->Rename(mFileName.c_str(), backname.c_str());
        }
        cTWUtil::WriteReport(mFileName.c_str(), reph, rep, pNewKey != NULL, pNewKey);
        return;
    }
    else if (mFileHeader.GetID() == cConfigFile::GetFileHeaderID())
    {
        TSTRING configText;

        iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE,
                                           _T("%s%s\n"),
                                           TSS_GetString(cTW, tw::STR_OPEN_CONFIG_FILE).c_str(),
                                           cDisplayEncoder::EncodeInline(mFileName).c_str());

        cTWUtil::ReadConfigText(mFileName.c_str(), configText);
        if (backup)
        {
            TSTRING backname = mFileName + iFSServices::GetInstance()->GetStandardBackupExtension();
            iFSServices::GetInstance()->Rename(mFileName.c_str(), backname.c_str());
        }

        cTWUtil::WriteConfigText(mFileName.c_str(), configText, pNewKey != NULL, pNewKey);

        return;
    }
    else if (mFileHeader.GetID() == cPolicyFile::GetFileHeaderID())
    {
        std::string policyText;

        iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE,
                                           _T("%s%s\n"),
                                           TSS_GetString(cTW, tw::STR_OPEN_POLICY_FILE).c_str(),
                                           cDisplayEncoder::EncodeInline(mFileName).c_str());

        cTWUtil::ReadPolicyText(mFileName.c_str(), policyText, pOldKey);
        if (backup)
        {
            TSTRING backname = mFileName + iFSServices::GetInstance()->GetStandardBackupExtension();
            iFSServices::GetInstance()->Rename(mFileName.c_str(), backname.c_str());
        }

        cTWUtil::WritePolicyText(mFileName.c_str(), policyText, pNewKey != NULL, pNewKey);

        return;
    }
}
コード例 #30
0
unsigned __stdcall _OpFileMoveThread(void *pVoid) {

  OPERATIONSTRUCT os  = *reinterpret_cast<POPERATIONSTRUCT>(pVoid);
  OPCALLBACKDATA ocd;
  TSTRINGLISTIT it    = os.Files.begin();
  UINT uiCurFile      = 1U;
  bool bAskOverwrite  = true;
  BOOL bCancelOp      = FALSE;
  TSTRING tsTemp;

 /*
  * If the destination directory is invalid,
  * it's probably been moved, or renamed
  * since its association with the application.
  * Prompt the user to see if they'd like to 
  * create it, or abort.
  */
  if (FALSE == PathIsDirectory(os.tsDest.c_str())) {

    INT_PTR iChoice = PrintMsgBox(os.hWnd, _T("extFileCopy")
                                  _T(" : Directory not found"),
                                  MB_YESNO | MB_ICONWARNING,
                                  _T("The destination directory:\n\n")
                                  _T("%s\n\nhas either been moved")
                                  _T(" or renamed since its association")
                                  _T(" with extFileCopy. Would you like")
                                  _T(" to create it?"),
                                  os.tsDest.c_str());
            
    switch (iChoice) {

      case IDYES:
      {
       /*
        * Attempt to create the directory.
        */
        if (FALSE == CreateDirectory(os.tsDest.c_str(), NULL)) {

         /*
          * We've failed miserably.
          * Can't copy any files to a non-existant
          * directory; done.
          */
          PrintMsgBox(os.hWnd, _T("extFileCopy : ERROR"),
                      MB_OK | MB_ICONSTOP,
                      _T("An error occurred while attempting")
                      _T(" to create the directory:\n\n%s.\n\n")
                      _T("The directory will be disassociated with")
                      _T("extFileCopy.\n\n")
                      _T("Win32 error: %d"),
                      os.tsDest.c_str(),
                      GetLastError());

          RegUtil_RemAssociatedDirectory(ExtensionFromList(os.Files), os.tsDest);

          goto mtFinish;
        }

      }
      break;

      case IDNO:
      {
       /*
        * User doesn't want to bother creating
        * the directory; We have to remove
        * the association in the registry.
        */
        PrintMsgBox(os.hWnd, _T("extFileCopy : Removing association"),
                    MB_OK | MB_ICONWARNING,
                    _T("The inaccessible directory:\n\n%s\n\nwill now")
                    _T(" be disassociated with extFileCopy."),
                    os.tsDest.c_str());

        RegUtil_RemAssociatedDirectory(ExtensionFromList(os.Files), os.tsDest);

        goto mtFinish;
      }
      break;

    }

  }

  os.pDlg->SetCancelPtr(&bCancelOp);

 /*
  * Set up the dialog UI
  */
  if (os.bCopy) {

    os.pDlg->SetWindowText(_T("Copying ..."));

  } else {

    os.pDlg->SetWindowText(_T("Moving ..."));

  }

  os.pDlg->SetElapsedTime(0);

  for(; it != os.Files.end(); it++) {

   /*
    * Check if the operation was cancelled
    * by the user
    */
    os.pMutex->Lock();

    if (TRUE == bCancelOp) {

      os.pMutex->Unlock();
      goto mtFinish;
    }

    os.pMutex->Unlock();

   /*
    * Update overall progress
    */
    INT64 iOverallPct = ((uiCurFile * 100) / os.Files.size());

    sprintf(tsTemp, _T("Overall Progress (file %d of %d) : %I64d%%"),
            uiCurFile++, os.Files.size(), iOverallPct);

    os.pDlg->SetOverallProgress(iOverallPct, tsTemp);

   /*
    * Update current file name
    */
    TSTRING tsShortFile = GetFileFromPath((*it));
    TSTRING tsDisplay   = tsShortFile;

   /*
    * Truncate file name if necessary
    */
    tsDisplay = FileGetCompactName(tsDisplay, PD_MAXCURFILE);
    
    sprintf(tsTemp, _T("Current file '%s' : %I64d%%"),
            tsDisplay.c_str(), 0LL);

    os.pDlg->SetCurrentProgress(0, tsTemp);

   /*
    * Reset transfer rate
    */
    os.pDlg->SetTransferRate(_T("Transfer Rate: calculating..."));
            
   /* 
    * If the resulting destination path is > MAX_PATH,
    * we've got to skip this file and tell the user.
    */
    TSTRING tsDest = PathConcatFile(os.tsDest, tsShortFile);

    if (MAX_PATH < tsDest.size()) {

      PrintMsgBox(os.hWnd, _T("extFileCopy : Can't copy file"),
                  MB_OK | MB_ICONWARNING,
                  _T("The following destination path:\n\n")
                  _T("%s\n\nis longer than MAX_PATH characters, and")
                  _T(" cannot be created."), tsDest.c_str());

      continue;

    }

   /*
    * Make sure the file doesn't exist; if it does,
    * we've got to prompt the user to overwrite.
    */
    if (-1 != GetFileAttributes(tsDest.c_str())) {

     /*
      * Yeah, the file exists.
      */
      if (bAskOverwrite) {

        OverwriteDlg dlg((*it), tsDest, 1 < os.Files.size());

        if (!dlg.DoModal(static_cast<HINSTANCE>(g_hModule),
                         MAKEINTRESOURCE(IDD_OVERWRITE),
                         os.pDlg->m_hWnd))
        {
          
          MessageBox(os.pDlg->m_hWnd, _T("A fatal internal error has occurred. Cannot continue.\n"),
                     _T("extFileCopy : ERROR"), MB_OK | MB_ICONSTOP);

          os.pDlg->CleanUp();
          _endthreadex(1);

        }

       /*
        * Find out what the user chose
        */
        switch (dlg.Result()) {

          case YES:
           /*
            * Ok to overwrite, but don't touch
            * bAskOverwrite.
            */            
          break;

          case YESTOALL:
           /*
            * Ok to overwrite ALL files.
            */
            bAskOverwrite = false;
          break;

          case NO:
           /*
            * Don't overwrite this file;
            * instead skip to the next.
            */
            continue;
          break;

          case CANCEL:
           /*
            * Forget it. We're outta here.
            */
            os.pMutex->Lock();
            bCancelOp = TRUE;
            os.pMutex->Unlock();
            goto mtFinish;
          break;

        }

      }

    }

   /*
    * File doesn't exist, or we don't
    * really care.  Continue normally
    */
    TSTRING tsCurFile = FileGetCompactName(tsShortFile.c_str(), PD_MAXCURFILE);

    ocd.pbCancel    = &bCancelOp;
    ocd.dwStartTime = (2 == uiCurFile) ? GetTickCount() : ocd.dwStartTime;
    ocd.dwLastTime  = (2 == uiCurFile) ? ocd.dwStartTime : ocd.dwLastTime;
    ocd.dwLastRate  = GetTickCount();
    ocd.iLastPct    = 0LL;
    ocd.iThroughput = 0LL;
    ocd.pDlg        = os.pDlg;
    ocd.pMutex      = os.pMutex;
    ocd.szCurFile   = tsCurFile.c_str();

    if (os.bCopy) {

     /*
      * This is a copy operation
      */
      if (0 == CopyFileEx((*it).c_str(), tsDest.c_str(), _Callback,
                           &ocd, &bCancelOp, 0UL))
      {

       /*
        * The copy operation has failed!
        * Let's tell the user, and then
        * if there's more than one file
        * being copied, ask the user if
        * they'd like to continue with
        * the next file. (If the error
        * didn't result from user abortion)
        */
        if (ERROR_REQUEST_ABORTED != GetLastError()) {

          INT_PTR iUser = ErrorPrompt(os.pDlg->m_hWnd, (*it), tsDest, 
                                    (1 < os.Files.size()) ? true : false, os.bCopy);

          if (1 < os.Files.size()) {

            if (IDYES == iUser) {

            /*
              * User wishes to try the next file.
              */
              continue;

            } else if (IDNO == iUser) {

              break;

            }

          } else {

            continue;

          }

        }

      }

    } else {

     /*
      * This is a move operation
      */
      if (0 == MoveFileWithProgress((*it).c_str(), tsDest.c_str(), _Callback,
                                    &ocd, MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING
                                    | MOVEFILE_WRITE_THROUGH))
      {

       /*
        * The move operation has failed!
        * Let's tell the user, and then
        * if there's more than one file
        * being copied, ask the user if
        * they'd like to continue with
        * the next file. (If the error
        * didn't result from user abortion)
        */
        if (ERROR_REQUEST_ABORTED != GetLastError()) {

          INT_PTR iUser = ErrorPrompt(os.pDlg->m_hWnd, (*it), tsDest,
                                      (1 < os.Files.size()) ? true : false, os.bCopy);

          if (1 < os.Files.size()) {

            if (IDYES == iUser) {

            /*
              * User wishes to try the next file.
              */
              continue;

            } else if (IDNO == iUser) {

              break;

            }

          } else {

            continue;

          }

        }

      }

    }

  }

mtFinish:

  os.pDlg->CleanUp();
  _endthreadex(0U);
  return 0U;
}