Example #1
0
void KeywordManager::WriteKeywordDataToFile()
{
	CFile keyword_data_file;

	BOOL ret=MakeSureDirectoryPathExists("Keyword Files\\");

	for(UINT i=0; i<v_all_project_keywords.size(); i++)
	{
		BOOL open_write = FALSE;

		char filename[256+1];
		strcpy(filename, "Keyword Files\\");
		CString project = v_all_project_keywords[i].m_project_name.c_str();
		project.Replace('\\','_');			// replace the backslash with _
		project.Replace('\'', '_');		// replace the single quote "'" with _
		project.Replace(' ', '_');
		project.Replace('-', '_');
		project.Replace('&', '_');
		project.Replace('!', '_');
		project.Replace('$', '_');
		project.Replace('@', '_');
		project.Replace('%', '_');
		project.Replace('(', '_');
		project.Replace(')', '_');
		project.Replace('+', '_');
		project.Replace('~', '_');
		project.Replace('*', '_');
		project.Replace('.', '_');
		project.Replace(',', '_');
		project.Replace('?', '_');
		project.Replace(':', '_');
		project.Replace(';', '_');
		project.Replace('"', '_');
		project.Replace('/', '_');
		strcat(filename, project);
		strcat(filename, ".kwd");
/*		
		CFile test;
		bool existed = test.Open(filename,CFile::modeRead);
		if(existed)
		{
			MessageBox(NULL,filename,"Bingo",MB_OK);
			test.Close();
		}
*/
		open_write = keyword_data_file.Open(filename,CFile::typeBinary|CFile::modeCreate|CFile::modeWrite|CFile::shareDenyNone);

		if(open_write==TRUE)
		{
			int buf_len = v_all_project_keywords[i].GetBufferLength();
			char *buf = new char[buf_len];

			v_all_project_keywords[i].WriteToBuffer(buf);

			keyword_data_file.Write(buf, buf_len);

			delete [] buf;

			keyword_data_file.Close();
		}
	}
}
Example #2
0
CString CDlgMainTabRss::GetCurrentFileCommentString()
{
	if (!m_pwndRssFeed || !::IsWindow(m_pwndRssFeed->m_hWnd))
	{
		return CString(_T(""));
	}
	
	POSITION Pos = NULL;

	if (m_pwndRssFeed->m_ListShowMode == LISTSTYLE_ICO)
	{
		Pos = m_pwndRssFeed->m_listIcoFeedItem.GetFirstSelectedItemPosition();
	}
	else if (m_pwndRssFeed->m_ListShowMode == LISTSTYLE_ITEM)
	{
		Pos = m_pwndRssFeed->m_listFeedItem.GetFirstSelectedItemPosition();
	}
	else if(m_pwndRssFeed->m_ListShowMode == LISTSTYLE_SINGLE)
	{
		Pos = m_pwndRssFeed->m_listSingleFeedItem.GetFirstSelectedItemPosition();
	}

	if (!Pos)
	{
		return CString(_T(""));
	}

	int nIndex;
	CRssFeed::Item* pItem;

	if (m_pwndRssFeed->m_ListShowMode == LISTSTYLE_ICO)
	{//ICO模式没有item
		nIndex = m_pwndRssFeed->m_listIcoFeedItem.GetNextSelectedItem(Pos);
		pItem = NULL;
	}
	else if (m_pwndRssFeed->m_ListShowMode == LISTSTYLE_ITEM)
	{
		nIndex = m_pwndRssFeed->m_listFeedItem.GetNextSelectedItem(Pos);
		pItem =  m_pwndRssFeed->m_listFeedItem.GetFeedItem(nIndex);
	}
	else if(m_pwndRssFeed->m_ListShowMode == LISTSTYLE_SINGLE)
	{
		nIndex = m_pwndRssFeed->m_listSingleFeedItem.GetNextSelectedItem(Pos);
		pItem =  m_pwndRssFeed->m_listSingleFeedItem.GetFeedItem(nIndex);
	}

	if (pItem && pItem->GetPartFile())
	{
		CPartFile * pPartFile = pItem->GetPartFile();
		
		CString strFileEd2k = CreateED2kLink(pPartFile, false);
		if( strFileEd2k.IsEmpty() )
		{
			return CString(_T(""));
		}

		bool bFileisFinished = true;
		if( pPartFile->IsKindOf(RUNTIME_CLASS(CPartFile)) )
		{
			if( ((CPartFile*)pPartFile)->GetStatus()!=PS_COMPLETE )
				bFileisFinished = false;
		}

		CString strCommentUrl = bFileisFinished ? thePrefs.m_strFinishedFileCommentUrl : thePrefs.m_strPartFileCommentUrl;
		strCommentUrl.Replace(_T("[ed2k]"),strFileEd2k);
		strCommentUrl.Replace(_T("|"), _T("%7C"));

		CString sVersion;
		sVersion.Format(_T("&v=%u"),VC_VERSION_BUILD);
		strCommentUrl += sVersion;
		return strCommentUrl;
	}
	else if (pItem)
	{
		CString strED2KUrl = pItem->m_strEnclosure;
		if( strED2KUrl.IsEmpty() || strED2KUrl.Left(7).CompareNoCase(_T("ed2k://")))
		{
			return CString(_T(""));
		}

		CString strCommentUrl = thePrefs.m_strPartFileCommentUrl;
		strCommentUrl.Replace(_T("[ed2k]"),strED2KUrl);
		strCommentUrl.Replace(_T("|"), _T("%7C"));

		CString sVersion;
		sVersion.Format(_T("&v=%u"),VC_VERSION_BUILD);
		strCommentUrl += sVersion;
		return strCommentUrl;
	}
	else
	{
		CRssFeed* pFeed;
		if (m_pwndRssFeed->m_ListShowMode == LISTSTYLE_ITEM)
		{
			pFeed = m_pwndRssFeed->m_listFeedItem.GetFeed(nIndex);
		}
		else if(m_pwndRssFeed->m_ListShowMode == LISTSTYLE_SINGLE)
		{
			pFeed = m_pwndRssFeed->m_listSingleFeedItem.GetFeed(nIndex);
		}
		
		if ( pFeed == NULL )
		{
			pFeed = m_pwndRssFeed->m_listFeedItem.GetBlankLineFeed(nIndex - 1);
		}

		if (pFeed)
		{
			CString strCommentUrl = pFeed->m_strFeedUrl;
			strCommentUrl.MakeLower();
			int nPos = strCommentUrl.Find(_T("/feed"));
			if (nPos != -1)
			{
				strCommentUrl = strCommentUrl.Left(nPos);
				strCommentUrl +=_T("/comments/");
				return strCommentUrl;	
			}
		}

		return CString();
		//CString strFilePath;
		//strFilePath = thePrefs.GetMuleDirectory(EMULE_CONFIGDIR) + _T("Default.htm");
		//return strFilePath;
	}
}
Example #3
0
void CCopyDlg::OnOK()
{
    if (::IsWindow(m_pLogDlg->GetSafeHwnd())&&(m_pLogDlg->IsWindowVisible()))
    {
        m_pLogDlg->SendMessage(WM_CLOSE);
        return;
    }
    m_bCancelled = true;
    // check if the status thread has already finished
    if ((m_pThread)&&(m_bThreadRunning))
    {
        WaitForSingleObject(m_pThread->m_hThread, 1000);
        if (m_bThreadRunning)
        {
            // we gave the thread a chance to quit. Since the thread didn't
            // listen to us we have to kill it.
            TerminateThread(m_pThread->m_hThread, (DWORD)-1);
            InterlockedExchange(&m_bThreadRunning, FALSE);
        }
    }

    CString id;
    GetDlgItemText(IDC_BUGID, id);
    CString sRevText;
    GetDlgItemText(IDC_COPYREVTEXT, sRevText);
    if (!m_ProjectProperties.CheckBugID(id))
    {
        ShowEditBalloon(IDC_BUGID, IDS_COMMITDLG_ONLYNUMBERS, IDS_ERR_ERROR, TTI_ERROR);
        return;
    }
    m_sLogMessage = m_cLogMessage.GetText();
    if ((m_ProjectProperties.bWarnIfNoIssue) && (id.IsEmpty() && !m_ProjectProperties.HasBugID(m_sLogMessage)))
    {
        CTaskDialog taskdlg(CString(MAKEINTRESOURCE(IDS_COMMITDLG_WARNNOISSUE_TASK1)),
                            CString(MAKEINTRESOURCE(IDS_COMMITDLG_WARNNOISSUE_TASK2)),
                            L"TortoiseSVN",
                            0,
                            TDF_USE_COMMAND_LINKS | TDF_ALLOW_DIALOG_CANCELLATION | TDF_POSITION_RELATIVE_TO_WINDOW | TDF_SIZE_TO_CONTENT);
        taskdlg.AddCommandControl(1, CString(MAKEINTRESOURCE(IDS_COMMITDLG_WARNNOISSUE_TASK3)));
        taskdlg.AddCommandControl(2, CString(MAKEINTRESOURCE(IDS_COMMITDLG_WARNNOISSUE_TASK4)));
        taskdlg.SetCommonButtons(TDCBF_CANCEL_BUTTON);
        taskdlg.SetDefaultCommandControl(2);
        taskdlg.SetMainIcon(TD_WARNING_ICON);
        if (taskdlg.DoModal(m_hWnd) != 1)
            return;
    }
    UpdateData(TRUE);

    if (GetCheckedRadioButton(IDC_COPYHEAD, IDC_COPYREV) == IDC_COPYHEAD)
        m_CopyRev = SVNRev(SVNRev::REV_HEAD);
    else if (GetCheckedRadioButton(IDC_COPYHEAD, IDC_COPYREV) == IDC_COPYWC)
        m_CopyRev = SVNRev(SVNRev::REV_WC);
    else
        m_CopyRev = SVNRev(sRevText);

    if (!m_CopyRev.IsValid())
    {
        ShowEditBalloon(IDC_COPYREVTEXT, IDS_ERR_INVALIDREV, IDS_ERR_ERROR, TTI_ERROR);
        return;
    }

    CString combourl = m_URLCombo.GetWindowString();
    if (combourl.IsEmpty())
        combourl = m_URLCombo.GetString();

    if ((m_wcURL.CompareNoCase(combourl)==0)&&(m_CopyRev.IsHead()))
    {
        CString temp;
        temp.FormatMessage(IDS_ERR_COPYITSELF, (LPCTSTR)m_wcURL, (LPCTSTR)m_URLCombo.GetString());
        ::MessageBox(this->m_hWnd, temp, L"TortoiseSVN", MB_ICONERROR);
        return;
    }

    m_URLCombo.SaveHistory();
    m_URL = CPathUtils::CombineUrls(m_repoRoot, m_URLCombo.GetString());
    if (!CTSVNPath(m_URL).IsValidOnWindows())
    {
        CString sInfo;
        sInfo.Format(IDS_WARN_NOVALIDPATH_TASK1, (LPCTSTR)m_URL);
        CTaskDialog taskdlg(sInfo,
                            CString(MAKEINTRESOURCE(IDS_WARN_NOVALIDPATH_TASK2)),
                            L"TortoiseSVN",
                            0,
                            TDF_ENABLE_HYPERLINKS | TDF_USE_COMMAND_LINKS | TDF_ALLOW_DIALOG_CANCELLATION | TDF_POSITION_RELATIVE_TO_WINDOW | TDF_SIZE_TO_CONTENT);
        taskdlg.AddCommandControl(1, CString(MAKEINTRESOURCE(IDS_WARN_NOVALIDPATH_TASK3)));
        taskdlg.AddCommandControl(2, CString(MAKEINTRESOURCE(IDS_WARN_NOVALIDPATH_TASK4)));
        taskdlg.SetCommonButtons(TDCBF_CANCEL_BUTTON);
        taskdlg.SetExpansionArea(CString(MAKEINTRESOURCE(IDS_WARN_NOVALIDPATH_TASK5)));
        taskdlg.SetDefaultCommandControl(2);
        taskdlg.SetMainIcon(TD_WARNING_ICON);
        if (taskdlg.DoModal(m_hWnd) != 1)
            return;
    }
    CStringUtils::WriteAsciiStringToClipboard(m_URL);

    // now let the bugtraq plugin check the commit message
    CComPtr<IBugTraqProvider2> pProvider2 = NULL;
    if (m_BugTraqProvider)
    {
        HRESULT hr = m_BugTraqProvider.QueryInterface(&pProvider2);
        if (SUCCEEDED(hr))
        {
            ATL::CComBSTR temp;
            ATL::CComBSTR sourceURL;
            sourceURL.Attach(m_wcURL.AllocSysString());
            ATL::CComBSTR parameters;
            parameters.Attach(m_bugtraq_association.GetParameters().AllocSysString());
            ATL::CComBSTR targetURL;
            targetURL.Attach(m_URL.AllocSysString());
            ATL::CComBSTR commitMessage;
            commitMessage.Attach(m_sLogMessage.AllocSysString());
            CBstrSafeVector pathList(1);
            pathList.PutElement(0, m_path.GetSVNPathString());

            hr = pProvider2->CheckCommit(GetSafeHwnd(), parameters, sourceURL, targetURL, pathList, commitMessage, &temp);
            if (FAILED(hr))
            {
                OnComError(hr);
            }
            else
            {
                CString sError = temp == 0 ? L"" : temp;
                if (!sError.IsEmpty())
                {
                    CAppUtils::ReportFailedHook(m_hWnd, sError);
                    return;
                }
            }
        }
    }

    CTSVNPathList checkedItems;
    checkedItems.AddPath(m_path);
    DWORD exitcode = 0;
    CString error;
    CHooks::Instance().SetProjectProperties(m_path, m_ProjectProperties);
    if (CHooks::Instance().CheckCommit(m_hWnd, checkedItems, m_sLogMessage, exitcode, error))
    {
        if (exitcode)
        {
            CString sErrorMsg;
            sErrorMsg.Format(IDS_HOOK_ERRORMSG, (LPCWSTR)error);

            CTaskDialog taskdlg(sErrorMsg,
                                CString(MAKEINTRESOURCE(IDS_HOOKFAILED_TASK2)),
                                L"TortoiseSVN",
                                0,
                                TDF_ENABLE_HYPERLINKS | TDF_USE_COMMAND_LINKS | TDF_ALLOW_DIALOG_CANCELLATION | TDF_POSITION_RELATIVE_TO_WINDOW | TDF_SIZE_TO_CONTENT);
            taskdlg.AddCommandControl(1, CString(MAKEINTRESOURCE(IDS_HOOKFAILED_TASK3)));
            taskdlg.AddCommandControl(2, CString(MAKEINTRESOURCE(IDS_HOOKFAILED_TASK4)));
            taskdlg.SetDefaultCommandControl(1);
            taskdlg.SetMainIcon(TD_ERROR_ICON);
            bool retry = (taskdlg.DoModal(GetSafeHwnd()) == 1);

            if (retry)
                return;
        }
    }

    if (!m_sLogMessage.IsEmpty())
    {
        m_History.AddEntry(m_sLogMessage);
        m_History.Save();
    }

    m_sBugID.Trim();
    if (!m_sBugID.IsEmpty())
    {
        m_sBugID.Replace(L", ", L",");
        m_sBugID.Replace(L" ,", L",");
        CString sBugID = m_ProjectProperties.sMessage;
        sBugID.Replace(L"%BUGID%", m_sBugID);
        if (m_ProjectProperties.bAppend)
            m_sLogMessage += L"\n" + sBugID + L"\n";
        else
            m_sLogMessage = sBugID + L"\n" + m_sLogMessage;
        UpdateData(FALSE);
    }
    CResizableStandAloneDialog::OnOK();
}
Example #4
0
void CAddCADFrameMenu::CreateMenus()
{
	CMDIFrameWnd * pMainFrame = acedGetAcadFrame();
	pMainFrame->LockWindowUpdate();

	//得到菜单栏上面的最后一个菜单
	CString sName;
	if(!GetLastMenuFromMenubar(sName))
		return;

	sName.Replace(_T("&"),_T(""));//debug

	IAcadMenuGroup *mnuGrp = NULL;
	if (!GetAcadMenuGroup(&mnuGrp,sName))
		return ;

	//得到所有菜单组
	IAcadPopupMenus   *mnus = NULL;
	IAcadPopupMenu   *mnu = NULL;
	IAcadPopupMenuItem  *mnuitem = NULL;
	HRESULT hr = S_OK;
	hr = mnuGrp->get_Menus(&mnus);
	long cnt = 0l;
	hr = mnus->get_Count(&cnt);
	int i = 0;
	int j = 0;
	int k = 0;
	VARIANT index;
	VariantInit(&index);
	V_VT(&index) = VT_I4;
	CArray<IAcadPopupMenu*, IAcadPopupMenu*> MnuAdrs; 

	long lIndex=0;
	for (i = 0; i < m_menuCount; i++) 
	{
		CString tmpMenu=m_TopMenuNames[i];
		tmpMenu.Replace(_T("&"),_T(""));
		if(IsMenuExist(mnu,lIndex,tmpMenu,mnus))//处理二次加载
		{
			V_I4(&index) = lIndex;
		}
		else
		{
			mnus->Add(m_TopMenuNames[i].AllocSysString(), &mnu);
			V_I4(&index) = cnt++;
		}

		MnuAdrs.Add(mnu);
		mnu->InsertInMenuBar(index);
	}

	IAcadPopupMenu *MenuItem = NULL;
	int subMenuNum = 0;
	CCADMenuArray* Menus;
	TCHAR szSubMenu[64];
	TCHAR szSubMenuMacro[64];
	CString MenusName;
	CString Menusorder;
	for (j = 0; j < m_menuCount; j++) {
		Menus = m_menus.GetAt(j);
		subMenuNum = Menus->GetSize();
		for (k = 0; k < subMenuNum; k++) { 
			mnu = MnuAdrs.GetAt(j);
			if (!_tcscmp(_T("--"), Menus->GetAt(k)->name)) {
				V_I4(&index) = k;
				mnu->AddSeparator(index, &mnuitem);
			}
			else {
				V_I4(&index) = k;    
				MenusName = Menus->GetAt(k)->name; 
				Menusorder = Menus->GetAt(k)->macro;

				if (_tcscspn(Menus->GetAt(k)->name, _T("*")) < (size_t)MenusName.GetLength()){
					MenusName.TrimLeft('*');
					hr = mnu->AddSubMenu(index, MenusName.AllocSysString(), &MenuItem);
				}    
				else if (_tcscspn(Menus->GetAt(k)->name, _T("$")) < (size_t)MenusName.GetLength() ){        
					MenusName.TrimLeft('$');
					if(MenusName.Compare(_T("--"))==0)//添加子菜单的分隔符
					{
						hr = MenuItem->AddSeparator(index, &mnuitem);
					}
					else
					{
						hr = MenuItem->AddMenuItem(index, MenusName.AllocSysString(), Menusorder.AllocSysString(), &mnuitem);
					}
				}
				else {
					hr = mnu->AddMenuItem(index,  MenusName.AllocSysString(), Menusorder.AllocSysString(), &mnuitem);
				}
			}
		}
	}

	for (i=0; i<MnuAdrs.GetSize(); i++)
	{
		MnuAdrs[i]->Release();
	}
	mnuitem->Release();
	mnus->Release();
	mnuGrp->Release();
	pMainFrame->UnlockWindowUpdate(); 

	stcMyTopMenuNames.Copy(m_TopMenuNames);//将顶级菜单名存入静态数组中,卸载时使用

	return ;
}
Example #5
0
BOOL CSwitchDlg::OnInitDialog()
{
	CResizableStandAloneDialog::OnInitDialog();

	ExtendFrameIntoClientArea(IDC_REVGROUP);
	m_aeroControls.SubclassOkCancelHelp(this);

	CTSVNPath svnPath(m_path);
	SetDlgItemText(IDC_SWITCHPATH, m_path);
	m_bFolder = svnPath.IsDirectory();
	SVN svn;
	CString sUUID;
	m_repoRoot = svn.GetRepositoryRootAndUUID(svnPath, true, sUUID);
	m_repoRoot.TrimRight('/');
	CString url = svn.GetURLFromPath(svnPath);
	m_URLCombo.LoadHistory(_T("Software\\TortoiseSVN\\History\\repoPaths\\")+sUUID, _T("url"));
	m_URLCombo.SetCurSel(0);
	if (!url.IsEmpty())
	{
		CString relPath = url.Mid(m_repoRoot.GetLength());
		CTSVNPath r = CTSVNPath(relPath);
		relPath = r.GetUIPathString();
		relPath.Replace('\\', '/');
		m_URLCombo.AddString(relPath, 0);
		m_URLCombo.SelectString(-1, relPath);
		m_URL = url;

		SetDlgItemText(IDC_DESTURL, CPathUtils::CombineUrls(m_repoRoot, relPath));
	}

	if (m_sTitle.IsEmpty())
		GetWindowText(m_sTitle);
	SetWindowText(m_sTitle);
	if (m_sLabel.IsEmpty())
		GetDlgItemText(IDC_URLLABEL, m_sLabel);
	SetDlgItemText(IDC_URLLABEL, m_sLabel);

	// set head revision as default revision
	SetRevision(SVNRev::REV_HEAD);

	m_depthCombo.AddString(CString(MAKEINTRESOURCE(IDS_SVN_DEPTH_WORKING)));
	m_depthCombo.AddString(CString(MAKEINTRESOURCE(IDS_SVN_DEPTH_INFINITE)));
	m_depthCombo.AddString(CString(MAKEINTRESOURCE(IDS_SVN_DEPTH_IMMEDIATE)));
	m_depthCombo.AddString(CString(MAKEINTRESOURCE(IDS_SVN_DEPTH_FILES)));
	m_depthCombo.AddString(CString(MAKEINTRESOURCE(IDS_SVN_DEPTH_EMPTY)));
	m_depthCombo.AddString(CString(MAKEINTRESOURCE(IDS_SVN_DEPTH_EXCLUDE)));
	m_depthCombo.SetCurSel(0);

	RECT rect;
	GetWindowRect(&rect);
	m_height = rect.bottom - rect.top;

	AddAnchor(IDC_SWITCHLABEL, TOP_LEFT, TOP_RIGHT);
	AddAnchor(IDC_SWITCHPATH, TOP_LEFT, TOP_RIGHT);
	AddAnchor(IDC_URLLABEL, TOP_LEFT, TOP_RIGHT);
	AddAnchor(IDC_URLCOMBO, TOP_LEFT, TOP_RIGHT);
	AddAnchor(IDC_BROWSE, TOP_RIGHT);
	AddAnchor(IDC_DESTLABEL, TOP_LEFT, TOP_RIGHT);
	AddAnchor(IDC_DESTURL, TOP_LEFT, TOP_RIGHT);
	AddAnchor(IDC_REVGROUP, TOP_LEFT);
	AddAnchor(IDC_REVISION_HEAD, TOP_LEFT);
	AddAnchor(IDC_REVISION_N, TOP_LEFT);
	AddAnchor(IDC_REVISION_NUM, TOP_LEFT);
	AddAnchor(IDC_LOG, TOP_LEFT);
	AddAnchor(IDC_GROUPMIDDLE, TOP_LEFT, TOP_RIGHT);
	AddAnchor(IDC_DEPTH, TOP_LEFT, TOP_RIGHT);
	AddAnchor(IDC_NOEXTERNALS, TOP_LEFT, TOP_RIGHT);
	AddAnchor(IDOK, BOTTOM_RIGHT);
	AddAnchor(IDCANCEL, BOTTOM_RIGHT);
	AddAnchor(IDHELP, BOTTOM_RIGHT);

	if ((m_pParentWnd==NULL)&&(hWndExplorer))
		CenterWindow(CWnd::FromHandle(hWndExplorer));
	EnableSaveRestore(_T("SwitchDlg"));
	return TRUE;
}
Example #6
0
LRESULT CClientListCtrl::OnP4ClientSpec(WPARAM wParam, LPARAM lParam)
{
	m_PrevNbrCli = m_UpdateState == LIST_CLEAR ? -1 : GetItemCount();
	m_saveclientnew = m_ClientNew;	// save name of freshly created client
	CCmd_EditSpec *pCmd = (CCmd_EditSpec *) wParam;

	if (pCmd->GetUseLocalDefTmplate())
	{
        CString specIn(pCmd->GetSpecIn());
		int i;
		if ((i = specIn.Find(_T("\n\nClient:\t"))) != -1)
		{
			CString tmplate = GET_P4REGPTR()->GetLocalCliTemplate();
			tmplate.Replace(LOCALDEFTEMPLATE, pCmd->GetItemName());
			pCmd->SetSpecIn(specIn.Left(i) + tmplate);
		}
	}

	m_ClientNew.Empty();

	// let the dialogbox know whether this is a new client or an edit of an existing one
	int index= FindInListAll(m_Active.IsEmpty() ? pCmd->GetItemName() : m_Active);
	if ((index == -1) || !GetItemCount())	// if name not in client list
		 index = m_NewClient ? -1 : -2;		//	it's new if and only if they clicked 'New'
	pCmd->SetIsNewClient(m_isNew = (index == -1));
	pCmd->SetIsRequestingNew(m_NewClicked);
	pCmd->SetOldClient(m_OldClient);
	pCmd->SetCaller(DYNAMIC_DOWNCAST(CView, GetParent()));
	m_NewClicked = m_NewClient = FALSE;	// clear these now, cuz no longer needed
    if (m_AddToViewList.GetCount() > 0)	// We have files to add to the Reviews list
	{
        CString specIn(pCmd->GetSpecIn());
		int i;
		if ((i = specIn.Find(_T("\n\nView:\n"))) == -1)
		{
			i = specIn.GetLength();
			specIn += _T("\n\nView:\n");
		}
		else
			specIn += _T("\[email protected]\[email protected]\n");	//	A view that is @[TAB]@ means
											//	put a blank line in the list here.
		POSITION pos;
		CString filename;
		CString localname;
		BOOL b = GET_P4REGPTR()->UseDepotInClientView();
		for (pos = m_AddToViewList.GetHeadPosition(); pos != NULL; )
		{
			filename = m_AddToViewList.GetNext(pos);
			if ((i = filename.Find(_T("<contains no files or folders>"))) != -1)
				filename = filename.Left(i-1) + _T("/...");
			localname = CString ( _T("//") ) + GET_P4REGPTR()->GetP4Client();
			if (!b && ((i = filename.Find(_T('/'), 2)) > 2))
				localname += filename.Right(filename.GetLength() - i);
			else
				localname += filename.Right(filename.GetLength() - 1);
			if (filename.Find(_T(' ')))
				filename = _T('\"') + filename + _T('\"');
			if (localname.Find(_T(' ')))
				localname = _T('\"') + localname + _T('\"');
			specIn += _T('\t') + filename + _T('\t') + localname + _T('\n');
		}
		m_AddToViewList.RemoveAll();		// this info is no longer needed
        pCmd->SetSpecIn(specIn);
	}
	// show the dialog box
	if(!pCmd->GetError() && !m_EditInProgress && pCmd->DoSpecDlg(this))
	{
		m_EditInProgress = TRUE;
		m_EditInProgressWnd = pCmd->GetSpecSheet();
	}
	else
	{
		if (GET_P4REGPTR()->GetExpandFlag() == 1)
			GET_P4REGPTR()->AddMRUPcuPath(MainFrame()->GetCurrentItemPath());
		m_Active = m_OldClient;
		GET_P4REGPTR()->SetP4Client( m_Active, TRUE, FALSE, FALSE);
		MainFrame()->UpdateCaption( ) ;	
        delete m_pNewSpec;

		if (pCmd->HaveServerLock())
			pCmd->ReleaseServerLock();
		delete pCmd;
	}

	MainFrame()->ClearStatus();
	return 0;
}
Example #7
0
CFieldValuePair::DumpARX(CARSConnection &arsConnect, CString Form, CStdioFile &File,
						CString &strAttachDir, unsigned int *p_uiAttachNum,
						CEntryId &EntryId, CString &strBuffer)
{
	// Insert a space before the value
//	File.Write(" ", 1);
	strBuffer += " ";

	CString cleanValue(Value);
	
	// dump the value to the file
	switch(uiType)
	{
	case AR_DATA_TYPE_NULL:
		//File.Write("\"\"", 2);
		strBuffer += "\"\"";
		break;
	// basically an value exported via this case will not have any double
		// quotes exported
	case AR_DATA_TYPE_INTEGER:
	case AR_DATA_TYPE_REAL:
	case AR_DATA_TYPE_ENUM:
	case AR_DATA_TYPE_TIME:
	case AR_DATA_TYPE_DECIMAL:
		//File.Write(LPCSTR(Value), Value.GetLength()); // write the value	
		strBuffer += Value;
		break;
		// any value exported via this case will have double quotes
		// inserted before and after the Value.
	case AR_DATA_TYPE_CHAR:
	case AR_DATA_TYPE_DIARY:
	case AR_DATA_TYPE_CURRENCY: // treat currency like a char because we need to double quotes
		cleanValue.Replace("\"", "\\\""); // insert a \ before each double quote
		cleanValue.Replace("\n", "\\r\\n"); // replace carriage returns with \r\n text
		//File.Write("\"", 1); // write double quote before value
		strBuffer += "\"";
		//File.Write(LPCSTR(cleanValue), cleanValue.GetLength()); // write the text value
		strBuffer += cleanValue;
		//File.Write("\"", 1); // write double quote after value
		strBuffer += "\"";
		break;
	case AR_DATA_TYPE_ATTACH:
		CString strExt; // working extenstion of the attachment
		CString strFile; // working file name with no extension
		CString strAttachNum; // working string for attachment number
		CString strFinishedAttach; // working completed attachment name to use when calling GetEntryBLOB()
		CString strFilePath; // the full path the the filename for saving the BLOB file

		// Save the file extension
		strExt = Value;
		strExt.MakeReverse();
		strExt = strExt.Left(4);
		strExt.MakeReverse();

		// Save the file name with out extenstion
		strFile = Value.Left(Value.GetLength() - 4);

		// convert the Attachment number to a string and increment it
		strAttachNum.Format("%d", *p_uiAttachNum);
		*p_uiAttachNum = *p_uiAttachNum + 1;

		// build the completed attachment name to save
//		strBuffer += "\"" + strAttachDir + "\\" + strFile + "_" + \
//			strAttachNum + strExt + "\"";
		strFinishedAttach = strAttachDir + "\\" + strFile + "_" + strAttachNum + strExt;
		strBuffer += "\"" + strFinishedAttach + "\"";

		// Lastly, save the attachment file BLOB
		// This function call needs the full path\filename to save the BLOB
		// this should be specified in strAttachFileName
		strFilePath = File.GetFilePath();
		strFilePath.Replace(File.GetFileName(), LPCSTR(strFinishedAttach)); // replace the filename with the relative attachment name
		DumpAttachment(arsConnect, Form, EntryId, uiFieldId, strFilePath);
		break;
	} // end switch
}
Example #8
0
void CExport::ConvertSpecialChars(CString &strString)
{
	strString.Replace( "@CR" , "\n" );
	strString.Replace( "@TAB" , "\t" );
}
Example #9
0
// strURL:			URL to encode.
// bEncodeReserved: Encode the reserved characters
//                  for example the ? character, which is used many times
//                  for arguments in URL.
//                  so if we are encoding just a string containing Keywords,
//                  we want to encode the reserved characters.
//                  but if we are encoding a simple URL, we wont.
CString CURLEncode::Encode(CString strURL, BOOL bEncodeReserved/*=FALSE*/)
{
	// First encode the % sign, because we are adding lots of it later...
	strURL.Replace(_T("%"), toHex(__toascii(_T('%'))));


	// Encdoe the reserved characters, if we choose to
	if (bEncodeReserved)
	{
		for (int i=0; i<m_iReservedLen; i++)
		{
			strURL.Replace(CString(m_lpszReservedString[i]), toHex(__toascii(m_lpszReservedString[i])));
		}
	}

	// Encode 'unsafe' characters
	// see: http://www.blooberry.com/indexdot/html/topics/urlencoding.htm
	for (int i=0; i<m_iUnsafeLen; i++)
	{
		strURL.Replace(CString(m_lpszUnsafeString[i]), toHex(__toascii(m_lpszUnsafeString[i])));
	}

	// Encode unprintable characters 0x00-0x1F, and 0x7F
	for (char c=0x00; c<=0x1F; c++)
	{
		strURL.Replace(CString(c), toHex(c));
	}
	strURL.Replace(CString((char)0x7F), toHex(0x7F));

	// Now encode all other unsafe characters
	TCHAR tc=0;
	WORD w=0;

	CString nc;
	// In this stage we do not want to convert:
	// 1. Characters A-Z, a-z, 0-9, because they are safe.
	// 2. The reserved characteres, we have already dealt with them;
	// 3. The % character...
	CString strDoNotReplace(m_lpszReservedString);
	strDoNotReplace.Append(_T("%"));

	for (int i=0; i<strURL.GetLength(); i++)
	{
		tc=strURL.GetAt(i);
		if ((tc<_T('a') || tc>_T('z')) && 
			(tc<_T('A') || tc>_T('Z')) &&
			(tc<_T('0') || tc>_T('9')) &&
			strDoNotReplace.Find(tc)<0)
		{
			w=toUTF8(tc);
			nc=toHex(HIBYTE(w));
			nc.Append(toHex(LOBYTE(w)));
			strURL.Replace(CString(tc), nc);
			// We have added 5 extra characters to the length of the string,
			// So we can ignore them.
			i+=5;
		}
	}

	return strURL;
}
Example #10
0
void m_EdInputVO2::OnBnClickedOk()
{
	char cQ[256] = "";
	long Ind = 0;
	SYSTEMTIME st;
	ZeroMemory(&st, sizeof(st));
	GetLocalTime(&st);
	
	char cY[10] = "";
	m_Dat.GetWindowText(cY, 10);
	WORD wYear = atoi(cY);

	if( wYear < 1900 || st.wYear < wYear )
	{
		AfxMessageBox("Год указан некорректно!");
		m_Dat.SetFocus();
		return;
	}

	if( st.wYear == wYear && st.wMonth < m_Cb.GetCurSel() + 1)
	{
		AfxMessageBox("Месяц введен некорректно!");
		m_Cb.SetFocus();
		return;
	}


	if( m_Check.GetCheck() )
	{
		FILE *f = fopen("html\\tmp.html", "w");
		if( !f ) 
		{
			AfxMessageBox("Невозможно открыть файл для сохранения отчета");
			return;
		}
		char ccc[5120] = "";
		sprintf(cQ, "pTov_mkcRepHTMVO2 %d, '%.2d%.2d01'", g_iDep, wYear, m_Cb.GetItemData(m_Cb.GetCurSel()));
		DBW.ExecSQL(cQ);
		for( int i = 0; i < 256 && (g_sqlret = DBW.Fetch())!= SQL_NO_DATA && g_sqlret != SQL_ERROR; i++ )
		{
			DBW.GetData(1, SQL_C_CHAR, ccc, 5120, &Ind);
			fprintf(f, "%s\n", ccc);
		}
		DBW.CloseCursor();
		fclose(f);
		ShellExecute(NULL, "open", "html\\tmp.html", NULL, NULL, SW_SHOWNORMAL);
		OnOK();
		return;

	}

	char rpt[60000] = "";
	char c = 0;
	FILE *f = fopen("html\\vo2_template.htm", "r");
	if( f )
	{
		c = fgetc(f);
		int i;
		for( i=0; i < 60000 && !feof(f); i++ )
		{			
			rpt[i] = c;
			c = fgetc(f);
		}
		fclose(f);
		rpt[i] = 0;
	}
	else
	{
		AfxMessageBox ("Невозможно открыть шаблон vo2_template.htm\nФормирование невозможно");
		return;
	}

	CString str = rpt;	
	strcpy(rpt, "N/A");

	sprintf(cQ, "pTov_mkcRepSelVO2S %d, '%.2d%.2d01'", g_iDep, wYear, m_Cb.GetItemData(m_Cb.GetCurSel()));
	DBW.ExecSQL(cQ);

	DBW.Fetch();
	DBW.GetData(1, SQL_C_CHAR, rpt, 100, &Ind );
	if( Ind != -1 ) str.Replace("###1###", rpt);
	else str.Replace("###1###", "N/A");
	DBW.GetData(2, SQL_C_CHAR, rpt, 100, &Ind );
	if( Ind != -1 )str.Replace("###2###", rpt);
	else str.Replace("###2###", "N/A");
	DBW.GetData(3, SQL_C_CHAR, rpt, 100, &Ind );
	if( Ind != -1 ) str.Replace("###3###", rpt);
	else str.Replace("###3###", "N/A");
	DBW.GetData(4, SQL_C_CHAR, rpt, 100, &Ind );
	if( Ind != -1 ) str.Replace("###4###", rpt);
	else str.Replace("###4###", "N/A");
	DBW.GetData(5, SQL_C_CHAR, rpt, 100, &Ind );
	if( Ind != -1 ) str.Replace("###5###", rpt);
	else str.Replace("###5###", "N/A");
	DBW.GetData(6, SQL_C_CHAR, rpt, 100, &Ind );
	if( Ind != -1 ) str.Replace("###6###", rpt);
	else str.Replace("###6###", "N/A");
	DBW.GetData(7, SQL_C_CHAR, rpt, 100, &Ind );
	if( Ind != -1 )str.Replace("###7###", rpt);
	else str.Replace("###7###", "N/A");
	DBW.GetData(8, SQL_C_CHAR, rpt, 100, &Ind );
	if( Ind != -1 ) str.Replace("###8###", rpt);
	else str.Replace("###8###", "N/A");

	DBW.GetData(9, SQL_C_CHAR, rpt, 100, &Ind );
	if( Ind != -1 )str.Replace("###9###", rpt);
	else str.Replace("###9###", "N/A");
	DBW.GetData(10, SQL_C_CHAR, rpt, 100, &Ind );
	if( Ind != -1 ) str.Replace("###10###", rpt);
	else str.Replace("###10###", "N/A");
	DBW.GetData(11, SQL_C_CHAR, rpt, 100, &Ind );
	if( Ind != -1 ) str.Replace("###11###", rpt);
	else str.Replace("###11###", "N/A");
	DBW.GetData(12, SQL_C_CHAR, rpt, 100, &Ind );
	if( Ind != -1 ) str.Replace("###12###", rpt);
	else str.Replace("###12###", "N/A");

	DBW.CloseCursor();
	f = fopen("html\\tmp.html", "w");
	fprintf(f, "%s", str);
	fclose(f);
	ShellExecute(NULL, "open", "html\\tmp.html", NULL, NULL, SW_SHOWNORMAL);
	OnOK();
}
Example #11
0
BOOL CFunctionView::UpdateFunctionInDocument()
{
    BOOL bRetVal    = FALSE;
    POSITION sStart = m_sStartPos;
    if ( sStart != NULL )
    {
        CFunctionEditorDoc* pDoc = (CFunctionEditorDoc*)CView::GetDocument();

        if ( pDoc != NULL )
        {
            SBUS_SPECIFIC_INFO sBusSpecInfo;
            pDoc->bGetBusSpecificInfo(sBusSpecInfo);
            //Construct the Function Footer
            CString omStrFnFooter;
            // If it is global variable then select Global variable footer
            if( m_omStrFnName == GLOBAL_VARIABLES )
            {
                omStrFnFooter = BUS_VAR_FOOTER;
                omStrFnFooter.Replace("PLACE_HODLER_FOR_BUSNAME", sBusSpecInfo.m_omBusName);
            }
            else
            {
                // Select function common footer
                omStrFnFooter = EDITOR_BUS_FN_FOOTER;
                // Form function specific footer
                omStrFnFooter.Replace("PLACE_HODLER_FOR_BUSNAME", sBusSpecInfo.m_omBusName);
                omStrFnFooter.Replace( "PLACE_HODLER_FOR_FUNCTIONNAME",
                                       m_omStrFnName );
            }

            CString omStrLine("");
            // Get the Edit control ref.
            CRichEditCtrl& romEditCtrl = GetRichEditCtrl();
            // get the total lines of code in the rich edit control
            int nLineCount      = romEditCtrl.GetLineCount();
            long lStart, lEnd;
            // Get the cursor position
            romEditCtrl.GetSel(lStart, lEnd);
            // Get the cursor line and save
            m_nCurrentLine = (int) romEditCtrl.LineFromChar(lStart);

            BOOL bDone = FALSE;

            pDoc->m_omSourceCodeTextList.GetNext(sStart);

            POSITION sPos1  = NULL;
            POSITION sPos2  = NULL;
            for( sPos1 = sStart; ( ((sPos2 = sPos1) != NULL) && (!bDone) ); )
            {
                CString omStrDel =
                    pDoc->m_omSourceCodeTextList.GetNext( sPos1 );
                if( omStrDel.Find(omStrFnFooter) >= 0 )
                {
                    bDone = TRUE;
                }
                else
                {
                    pDoc->m_omSourceCodeTextList.RemoveAt( sPos2 );
                }
            }

            BOOL bFirst = TRUE;
            POSITION sPos = m_sStartPos;


            for (int nLineIndex = 0; nLineIndex < nLineCount; nLineIndex++)
            {
                CString omStrNewItem("");

                int nCharIndex  = GetRichEditCtrl().LineIndex(nLineIndex);
                int nLineLength = GetRichEditCtrl().LineLength(nCharIndex);

                nLineLength = ( nLineLength < 4 ) ? 4 : nLineLength;

                GetRichEditCtrl().GetLine(nLineIndex,
                                          omStrNewItem.GetBuffer(nLineLength),
                                          nLineLength);

                omStrNewItem.ReleaseBuffer(nLineLength);
                omStrNewItem.TrimRight();



                if ( bFirst )
                {
                    pDoc->m_omSourceCodeTextList.SetAt(sPos, omStrNewItem);
                    bFirst = FALSE;
                }
                else
                {
                    pDoc->m_omSourceCodeTextList.InsertAfter(
                        sPos, omStrNewItem);
                    pDoc->m_omSourceCodeTextList.GetNext(sPos);
                }


            }
            bRetVal = TRUE;
        }
    }
    return bRetVal;
}
Example #12
0
int OpenControlChannel(char *hostname, int port, char *username, char *password, int timeout, char *retrfile, 
					   int ptype, char *pserver, int pport, char *puid, char *ppwd, char *szReturn, CFtpParam& ftpParam)
{
	struct	sockaddr_in	sa;
	struct	hostent		*hp;
	char	buffer[1024] = {0};
	int		ret = 0;
	CString	strCmd = _T("");
	CString strMessage = _T("");

	if(*pserver)
	{
		// Use Proxy
		switch(ptype)
		{
		case 0:
			// Common Proxy
			hp = gethostbyname(pserver);
			if(!hp)
			{
				sprintf(szReturn, "error=%s$",  FuncGetStringFromIDS("SV_PROXY",
                    "PROXY_DOMAIN_NAME_PARSER_ERROR"));//<%IDS_FTP_1%>
				return 1;
			}

			memcpy(&sa.sin_addr,hp->h_addr_list[0],hp->h_length);
			sa.sin_family = AF_INET;
			sa.sin_port=htons(pport);
			if (connect_timeo(ftpParam.ctrlSocket, (struct sockaddr *)&sa, sizeof(sa), timeout))
			{
				shutdown(ftpParam.ctrlSocket, 0x02);
				closesocket(ftpParam.ctrlSocket);
				sprintf(szReturn, "error=%s$", FuncGetStringFromIDS("SV_PROXY",
                    "PROXY_CONNECT_FAILED"));//<%IDS_FTP_2%>
				return 1;
			}
			break;
		case 1:
			// Socks5 Proxy
			if(socks5_protocol(ftpParam.ctrlSocket, hostname, port, pserver, pport, puid, ppwd, timeout))
			{
				sprintf(szReturn, "error=%s$", FuncGetStringFromIDS("SV_PROXY",
                    "PROXY_SERVER_ERROR"));//<%IDS_FTP_3%>
				return 1;
			}
			break;
		default:
			sprintf(szReturn, "error=%s$", FuncGetStringFromIDS("SV_FTP",
                "FTP_UNKNOWN_PROXY_TYPE"));//<%IDS_FTP_4%>
			return 1;
		}
	}
	else
	{
		// Direct Connect
		hp = gethostbyname(hostname);
		if(!hp)	
		{
			sprintf(szReturn, "error=%s$", FuncGetStringFromIDS("SV_DNS",
                "DNS_DOMAIN_NAME_PARSE_ERROR"));//<%IDS_FTP_5%>
			return 1;
		}

		memcpy(&sa.sin_addr,hp->h_addr_list[0],hp->h_length);
		sa.sin_family = AF_INET;
		sa.sin_port=htons(port);
		if (connect_timeo(ftpParam.ctrlSocket, (struct sockaddr *)&sa, sizeof(sa), timeout))
		{
			shutdown(ftpParam.ctrlSocket, 0x02);
			closesocket(ftpParam.ctrlSocket);
			sprintf(szReturn, "error=%s$", FuncGetStringFromIDS("SV_FTP",
                "FTP_CONNET_FAILED"));//<%IDS_FTP_6%>
			return 1;
		}
	}

	CString	retMsg = _T("");
	if(WaitVersionInfo(ftpParam.ctrlSocket, timeout))
	{
		sprintf(szReturn, "error=%s$", FuncGetStringFromIDS("SV_FTP",
            "FTP_WAIT_INIT_INFO_TIMEOUT"));//<%IDS_FTP_7%>
		return 1;
	}

	// Send USER Command
	if(*pserver && ptype == 0)
		strCmd.Format("USER %[email protected]%s\r\n", username, hostname);
	else
		strCmd.Format("USER %s\r\n", username);
	ret = FTP_COMMAND(ftpParam.ctrlSocket, strCmd, strMessage);
	if(ret != 2 && ret != 3)
	{
		sprintf(szReturn, "error=%s$", FuncGetStringFromIDS("SV_FTP",
            "FTP_SEND_USERNAME_FAILED"));//<%IDS_FTP_8%>
		return 1;
	}

	// Send PASS Command
	strCmd.Format("PASS %s\r\n", password);
	ret = FTP_COMMAND(ftpParam.ctrlSocket, strCmd, strMessage);
	if(ret != 2 && ret != 3)
	{
		sprintf(szReturn, "error=%s$", FuncGetStringFromIDS("SV_FTP",
            "FTP_SEND_PWD_FAILED"));//<%IDS_FTP_9%>
		return 1;
	}

	// Binary Mode
	strCmd = "TYPE I\r\n";
	ret = FTP_COMMAND(ftpParam.ctrlSocket, strCmd, strMessage);
	if(ret != 2 && ret != 3)
	{
		sprintf(szReturn, "error=%s$", FuncGetStringFromIDS("SV_FTP",
            "FTP_APPLY_BINARY_MODE_ERROR"));//<%IDS_FTP_10%>
		return 1;
	}

	if(ftpParam.passive_mode)
	{
		// Passive Mode
		if(EnterPassiveMode(ftpParam))
		{
			sprintf(szReturn, "error=%s$", FuncGetStringFromIDS("SV_FTP",
                "FTP_APPLY_PASSIVITY_MODE_ERROR"));//<%IDS_FTP_11%>
			return 1;
		}
	}
	else
	{
		int Count = 0;
		while(1)
		{
			ftpParam.local_port = rand() % 55536 + 10000;
			
			sa.sin_family = AF_INET;
			sa.sin_addr.s_addr = htonl(INADDR_ANY);
			sa.sin_port=htons(ftpParam.local_port);
			if(bind(ftpParam.dataSocket, (struct sockaddr *)&sa, sizeof(sa)) == SOCKET_ERROR)
			{
				if(Count < 5)
				{
					Count ++;
					continue;
				}
				else
				{
					sprintf(szReturn, "error=%s$", FuncGetStringFromIDS("SV_FTP",
                        "FTP_LOCATE_BIND_ERROR"));//<%IDS_FTP_12%>
					return 1;
				}
			}

			if(listen(ftpParam.dataSocket, 10) == SOCKET_ERROR)
			{
				if(Count < 5)
				{
					Count ++;
					continue;
				}
				else
				{
					sprintf(szReturn, "error=%s$", FuncGetStringFromIDS("SV_FTP",
                        "FTP_LOCATE_CREATE_COMMUNICATE_ERROR"));//<%IDS_FTP_13%>
					return 1;
				}
			}

			break;
		}

		struct sockaddr_in lsa;
		int salen = sizeof(lsa);
		if(getsockname(ftpParam.ctrlSocket, (struct sockaddr *)&lsa, &salen) == SOCKET_ERROR)
		{
			sprintf(szReturn, "error=%s$", FuncGetStringFromIDS("SV_FTP",
                "FTP_GET_LOCATE_INFO_ERROR"));//<%IDS_FTP_14%>
			return 1;
		}
		strcpy(ftpParam.local_host, inet_ntoa(lsa.sin_addr));
		strCmd.Format("PORT %s,%d,%d\r\n", ftpParam.local_host, ftpParam.local_port/256, ftpParam.local_port%256);
		strCmd.Replace('.', ',');
		ret = FTP_COMMAND(ftpParam.ctrlSocket, strCmd, strMessage);
		if(ret < 0 || ret != 2)
		{
			if(!ftpParam.passive_mode)
			{
				//closesocket(dataSocket);
				ftpParam.passive_mode = 1;
				if(EnterPassiveMode(ftpParam))
				{
					sprintf(szReturn, "error=%s$", FuncGetStringFromIDS("SV_FTP",
                        "FTP_APPLY_PASSIVITY_MODE_ERROR"));//<%IDS_FTP_15%>
					return 1;
				}
			}
		}
	}

    if(strlen(retrfile) > 0)
    {
	    strCmd.Format("RETR %s\r\n", retrfile);
	    WriteString(ftpParam.ctrlSocket, strCmd);
	    ret = ReadString2(ftpParam.ctrlSocket,buffer);
	    if(ret != 1 && ret != 2 && ret != 3 && ret != 9)
	    {
		    if(ret == 5)
			    sprintf(szReturn, "error=%s$", FuncGetStringFromIDS("SV_FTP",
                "FTP_FILE_NOT_FOUND"));//<%IDS_FTP_16%>
		    else
			    sprintf(szReturn, "error=%s$", FuncGetStringFromIDS("SV_FTP",
                "FTP_UNKNOWN_ERROR"));//<%IDS_FTP_17%>
		    return 1;
	    }
    }

	return 0;
}
Example #13
0
// This method sends the report over Simple MAPI
BOOL CErrorReportSender::SendOverSMAPI()
{  
  strconv_t strconv;

  if(g_CrashInfo.m_sEmailTo.IsEmpty())
  {
    m_Assync.SetProgress(_T("No E-mail address is specified for sending error report over Simple MAPI; skipping."), 0);
    return FALSE;
  }

  if(g_CrashInfo.m_bSilentMode)
  {
    m_Assync.SetProgress(_T("Simple MAPI may require user interaction (not acceptable for non-GUI mode); skipping."), 0);
    return FALSE;
  }

  m_Assync.SetProgress(_T("Sending error report using Simple MAPI"), 0, false);
  m_Assync.SetProgress(_T("Initializing MAPI"), 1);

  BOOL bMAPIInit = m_MapiSender.MAPIInitialize();
  if(!bMAPIInit)
  {
    m_Assync.SetProgress(m_MapiSender.GetLastErrorMsg(), 100, false);
    return FALSE;
  }
  
  if(m_SendAttempt!=0)
  {
    m_Assync.SetProgress(_T("[confirm_launch_email_client]"), 0);
    int confirm = 1;
    m_Assync.WaitForFeedback(confirm);
    if(confirm!=0)
    {
      m_Assync.SetProgress(_T("Cancelled by user"), 100, false);
      return FALSE;
    }
  }

  CString msg;
  CString sMailClientName;
  m_MapiSender.DetectMailClient(sMailClientName);
  
  msg.Format(_T("Launching the default email client (%s)"), sMailClientName);
  m_Assync.SetProgress(msg, 10);

  m_MapiSender.SetFrom(g_CrashInfo.m_sEmailFrom);
  m_MapiSender.SetTo(g_CrashInfo.m_sEmailTo);
  m_MapiSender.SetSubject(g_CrashInfo.m_sEmailSubject);
  CString sFileTitle = m_sZipName;
  sFileTitle.Replace('/', '\\');
  int pos = sFileTitle.ReverseFind('\\');
  if(pos>=0)
    sFileTitle = sFileTitle.Mid(pos+1);
    
  m_MapiSender.SetMessage(FormatEmailText());
  m_MapiSender.AddAttachment(m_sZipName, sFileTitle);

  // Create and attach MD5 hash file
  CString sErrorRptHash;
  CalcFileMD5Hash(m_sZipName, sErrorRptHash);
  sFileTitle += _T(".md5");
  CString sTempDir;
  Utility::getTempDirectory(sTempDir);
  CString sTmpFileName = sTempDir +_T("\\")+ sFileTitle;
  FILE* f = NULL;
  _TFOPEN_S(f, sTmpFileName, _T("wt"));
  if(f!=NULL)
  { 
    LPCSTR szErrorRptHash = strconv.t2a(sErrorRptHash.GetBuffer(0));
    fwrite(szErrorRptHash, strlen(szErrorRptHash), 1, f);
    fclose(f);
    m_MapiSender.AddAttachment(sTmpFileName, sFileTitle);  
  }
  
  BOOL bSend = m_MapiSender.Send();
  if(!bSend)
    m_Assync.SetProgress(m_MapiSender.GetLastErrorMsg(), 100, false);
  else
    m_Assync.SetProgress(_T("Sent OK"), 100, false);
  
  return bSend;
}
Example #14
0
bool CHooks::ParseAndInsertProjectProperty( hooktype t, const CString& strhook, const CTSVNPath& wcRootPath, const CString& rootPath, const CString& rootUrl, const CString& repoRootUrl )
{
    if (strhook.IsEmpty())
        return false;
    // the string consists of multiple lines, where one hook script is defined
    // as four lines:
    // line 1: command line to execute
    // line 2: 'true' or 'false' for waiting for the script to finish
    // line 3: 'show' or 'hide' on how to start the hook script
    // line 4: 'force' on whether to ask the user for permission
    hookkey key;
    hookcmd cmd;

    key.htype = t;
    key.path = wcRootPath;

    int pos = 0;
    CString temp;

    temp = strhook.Tokenize(L"\n", pos);
    if (!temp.IsEmpty())
    {
        ASSERT(t == GetHookType(temp));
        temp = strhook.Tokenize(L"\n", pos);
        if (!temp.IsEmpty())
        {
            int urlstart = temp.Find(L"%REPOROOT%");
            if (urlstart >= 0)
            {
                temp.Replace(L"%REPOROOT%", repoRootUrl);
                CString fullUrl = temp.Mid(urlstart);
                int urlend = -1;
                if ((urlstart > 0)&&(temp[urlstart-1]=='\"'))
                    urlend = temp.Find('\"', urlstart);
                else
                    urlend = temp.Find(' ', urlstart);
                if (urlend < 0)
                    urlend = temp.GetLength();
                fullUrl = temp.Mid(urlstart, urlend-urlstart);
                fullUrl.Replace('\\', '/');
                // now we have the full url of the script, e.g.
                // https://svn.osdn.net/svnroot/tortoisesvn/trunk/contrib/hook-scripts/client-side/checkyear.js

                CString sLocalPathUrl = rootUrl;
                CString sLocalPath = rootPath;
                // find the lowest common ancestor of the local path url and the script url
                while (fullUrl.Left(sLocalPathUrl.GetLength()).Compare(sLocalPathUrl))
                {
                    int sp = sLocalPathUrl.ReverseFind('/');
                    if (sp < 0)
                        return false;
                    sLocalPathUrl = sLocalPathUrl.Left(sp);

                    sp = sLocalPath.ReverseFind('\\');
                    if (sp < 0)
                        return false;
                    sLocalPath = sLocalPath.Left(sp);
                }
                // now both sLocalPathUrl and sLocalPath can be used to construct
                // the path to the script
                CString partUrl = fullUrl.Mid(sLocalPathUrl.GetLength());
                if (partUrl.Find('/') == 0)
                    partUrl = partUrl.Mid(1);
                if (sLocalPath.ReverseFind('\\') == sLocalPath.GetLength() - 1 || sLocalPath.ReverseFind('/') == sLocalPath.GetLength() - 1)
                    sLocalPath = sLocalPath.Left(sLocalPath.GetLength() - 1);
                sLocalPath = sLocalPath + L"\\" + partUrl;
                sLocalPath.Replace('/', '\\');
                // now replace the full url in the command line with the local path
                temp.Replace(fullUrl, sLocalPath);
            }
            urlstart = temp.Find(L"%REPOROOT+%");
            if (urlstart >= 0)
            {
                CString temp2 = temp;
                CString sExt = rootUrl.Mid(repoRootUrl.GetLength());
                CString sLocalPath;
                do
                {
                    temp = temp2;
                    CString repoRootUrlExt = repoRootUrl + sExt;
                    int slp = sExt.ReverseFind('/');
                    if (slp >= 0)
                        sExt = sExt.Left(sExt.ReverseFind('/'));
                    else if (sExt.IsEmpty())
                        return false;
                    else
                        sExt.Empty();
                    temp.Replace(L"%REPOROOT+%", repoRootUrlExt);
                    CString fullUrl = temp.Mid(urlstart);
                    int urlend = -1;
                    if ((urlstart > 0)&&(temp[urlstart-1]=='\"'))
                        urlend = temp.Find('\"', urlstart);
                    else
                        urlend = temp.Find(' ', urlstart);
                    if (urlend < 0)
                        urlend = temp.GetLength();
                    fullUrl = temp.Mid(urlstart, urlend-urlstart);
                    fullUrl.Replace('\\', '/');
                    // now we have the full url of the script, e.g.
                    // https://svn.osdn.net/svnroot/tortoisesvn/trunk/contrib/hook-scripts/client-side/checkyear.js

                    CString sLocalPathUrl = rootUrl;
                    sLocalPath = rootPath;
                    // find the lowest common ancestor of the local path url and the script url
                    while (fullUrl.Left(sLocalPathUrl.GetLength()).Compare(sLocalPathUrl))
                    {
                        int sp = sLocalPathUrl.ReverseFind('/');
                        if (sp < 0)
                            return false;
                        sLocalPathUrl = sLocalPathUrl.Left(sp);

                        sp = sLocalPath.ReverseFind('\\');
                        if (sp < 0)
                            return false;
                        sLocalPath = sLocalPath.Left(sp);
                    }
                    // now both sLocalPathUrl and sLocalPath can be used to construct
                    // the path to the script
                    CString partUrl = fullUrl.Mid(sLocalPathUrl.GetLength());
                    if (partUrl.Find('/') == 0)
                        partUrl = partUrl.Mid(1);
                    if (sLocalPath.ReverseFind('\\') == sLocalPath.GetLength() - 1 || sLocalPath.ReverseFind('/') == sLocalPath.GetLength() - 1)
                        sLocalPath = sLocalPath.Left(sLocalPath.GetLength() - 1);
                    sLocalPath = sLocalPath + L"\\" + partUrl;
                    sLocalPath.Replace('/', '\\');
                    // now replace the full url in the command line with the local path
                    temp.Replace(fullUrl, sLocalPath);
                } while (!PathFileExists(sLocalPath));
            }
            cmd.commandline = temp;
            temp = strhook.Tokenize(L"\n", pos);
            if (!temp.IsEmpty())
            {
                cmd.bWait = (temp.CompareNoCase(L"true")==0);
                temp = strhook.Tokenize(L"\n", pos);
                if (!temp.IsEmpty())
                {
                    cmd.bShow = (temp.CompareNoCase(L"show")==0);

                    temp.Format(L"%d%s", (int)key.htype, (LPCTSTR)cmd.commandline);
                    SVNPool pool;
                    cmd.sRegKey = L"Software\\TortoiseSVN\\approvedhooks\\" + SVN::GetChecksumString(svn_checksum_sha1, temp, pool);
                    CRegDWORD reg(cmd.sRegKey, 0);
                    cmd.bApproved = (DWORD(reg) != 0);
                    cmd.bStored = reg.exists();

                    temp = strhook.Tokenize(L"\n", pos);
                    cmd.bEnforce = temp.CompareNoCase(L"enforce")==0;

                    if (find(key) == end())
                    {
                        m_pInstance->insert(std::pair<hookkey, hookcmd>(key, cmd));
                        return true;
                    }
                }
            }
        }
    }
    return false;
}
Example #15
0
void CRCFile::ProcessMenu(UINT uiMenuID, std::vector<CString>::iterator *init)
{
    element_map* pElementMap = GetElementMap(uiMenuID);
    if(!pElementMap)
        return;

    CString str;
    for (; (*init) != m_vInRCFile.end(); (*init)++)
    {
        str=**init;
        str.TrimLeft(_T(" "));
        str.TrimRight(_T(" "));

        // check for exit
        if ( str == _T("END") )
        {
            // add the line to the outrc wo changes
            m_vOutRCFile.push_back(**init);
            return;
        }
        else if (str.Left(5) == _T("POPUP")) // if that is the popup string - call the function once more
        {
            // add the line to the outrc with changes - replace string inside "" with P
            str=**init;

            // processing menuitem - find the text
            int iPos=str.Find(_T("\""), 0);
            CString strText;
            if (iPos != -1)
            {
                strText=str.Mid(iPos+1);
                int iPos2=strText.Find(_T("\""));
                if (iPos2 != -1)
                    strText=strText.Left(iPos2);
            }

            // now find the | that separates the text from the pseudo-ID
            int iBar=strText.ReverseFind(_T('|'));
            if (iBar != -1)
            {
                // there is a text with an ID
                CString strID=strText.Mid(iBar+1);
                strText=strText.Left(iBar);

                // put the id and text in the translation file
                // find the equiv for the id
                UINT uiID = GetResourceID(strID);
                pElementMap->insert(std::make_pair(uiID, strText));

                // put the found ID as output text
                CString out;
                out.Format(_T("\"%lu\""), uiID);
                str=str.Left(iPos)+out;
            }
            else
            {
                // no pseudoID in menu name
                str=str.Left(iPos)+_T("\"P\"");
            }

            m_vOutRCFile.push_back(str);

            (*init)++;
            ProcessMenu(uiMenuID, init);
        }
        else
        {
            // if the line has MENUITEM
            if (str.Left(8) == _T("MENUITEM") && str.Right(9) != _T("SEPARATOR"))
            {
                // restore original
                str=**init;

                // check if there is any text after the comma
                int iPos=str.Find(_T(","), 0);
                CString strTest=str.Mid(iPos);
                strTest.TrimLeft(_T(" ,\t\r\n"));
                if (strTest.IsEmpty())
                {
                    (*init)++;

                    CString tmp=**init;
                    tmp.Trim(_T(" ,\t\r\n"));
                    str+=tmp;
                }

                // processing menuitem - find the text
                iPos=str.Find(_T("\""), 0);
                CString strText;
                if (iPos != -1)
                {
                    strText=str.Mid(iPos+1);
                    int iPos2=strText.Find(_T("\""));
                    if (iPos2 != -1)
                        strText=strText.Left(iPos2);
                }

                // find the ID
                iPos=str.Find(_T(","), 0);
                CString strID;
                if (iPos != -1)
                {
                    strID=str.Mid(iPos+1);
                    int iPos2=strID.Find(_T(","), 0);
                    if (iPos2 != -1)
                        strID=strID.Left(iPos2);
                }
                strID.TrimLeft(_T(" \t"));
                strID.TrimRight(_T(" \t"));

                // find the equiv for the id
                UINT uiID = GetResourceID(strID);
                pElementMap->insert(std::make_pair(uiID, strText));
                CString out = str;
                //				out=**init;
                out.Replace(_T("\"")+strText+_T("\""), _T("\"i\""));
                m_vOutRCFile.push_back(out);
            }
            else
                m_vOutRCFile.push_back(**init);
        }
    }
}
Example #16
0
void CPlaylistItem::AutoLoadFiles()
{
    if (m_fns.IsEmpty()) {
        return;
    }

    const CAppSettings& s = AfxGetAppSettings();

    CString fn = m_fns.GetHead();

    if (s.fAutoloadAudio && fn.Find(_T("://")) < 0) {
        int i = fn.ReverseFind('.');
        if (i > 0) {
            const CMediaFormats& mf = s.m_Formats;

            CString ext = fn.Mid(i + 1).MakeLower();

            if (!mf.FindExt(ext, true)) {
                CString path = fn;
                path.Replace('/', '\\');
                path = path.Left(path.ReverseFind('\\') + 1);

                WIN32_FIND_DATA fd;
                ZeroMemory(&fd, sizeof(WIN32_FIND_DATA));
                HANDLE hFind = FindFirstFile(fn.Left(i) + _T("*.*"), &fd);
                if (hFind != INVALID_HANDLE_VALUE) {
                    do {
                        if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
                            continue;
                        }

                        CString fullpath = path + fd.cFileName;
                        CString ext2 = fullpath.Mid(fullpath.ReverseFind('.') + 1).MakeLower();
                        if (!FindFileInList(m_fns, fullpath) && ext != ext2
                                && mf.FindExt(ext2, true) && mf.IsUsingEngine(fullpath, DirectShow)) {
                            m_fns.AddTail(fullpath);
                        }
                    } while (FindNextFile(hFind, &fd));

                    FindClose(hFind);
                }
            }
        }
    }

    if (s.IsISRAutoLoadEnabled()) {
        const CString& pathList = s.strSubtitlePaths;

        CAtlArray<CString> paths;

        int pos = 0;
        do {
            CString path = pathList.Tokenize(_T(";"), pos);
            if (!path.IsEmpty()) {
                paths.Add(path);
            }
        } while (pos != -1);

        CString dir = fn;
        dir.Replace('\\', '/');
        int l  = dir.ReverseFind('/') + 1;
        int l2 = dir.ReverseFind('.');
        if (l2 < l) { // no extension, read to the end
            l2 = fn.GetLength();
        }
        CString title = dir.Mid(l, l2 - l);
        paths.Add(title);

        CAtlArray<Subtitle::SubFile> ret;
        Subtitle::GetSubFileNames(fn, paths, ret);

        for (size_t i = 0; i < ret.GetCount(); i++) {
            if (!FindFileInList(m_subs, ret[i].fn)) {
                m_subs.AddTail(ret[i].fn);
            }
        }
    }
}
Example #17
0
void CRCFile::ProcessDialog(UINT uiDialogID, std::vector<CString>::iterator *init)
{
    element_map* pElementMap = GetElementMap(uiDialogID);
    if(!pElementMap)
        return;

    CString str;
    for (; (*init) != m_vInRCFile.end(); (*init)++)
    {
        str=**init;
        str.TrimLeft(_T(" "));
        str.TrimRight(_T(" "));

        // check for exit
        if ( str == _T("END") )
        {
            // add the line to the outrc wo changes
            m_vOutRCFile.push_back(**init);
            return;
        }
        else if ( str.Left(7) == _T("CAPTION") )
        {
            // read the caption
            CString strText=str.Mid(7);
            strText.TrimLeft(_T(" \t\""));
            strText.TrimRight(_T(" \t\""));

            pElementMap->insert(std::make_pair(0, strText));

            // save to rc wo title
            str=**init;
            str.Replace(_T("\"")+strText+_T("\""), _T("\"\""));
            m_vOutRCFile.push_back(str);
        }
        else if ( str.Left(5) == _T("LTEXT") || str.Left(5) == _T("CTEXT") || str.Left(5) == _T("RTEXT") || str.Left(13) == _T("DEFPUSHBUTTON") || str.Left(10) == _T("PUSHBUTTON") || str.Left(7) == _T("CONTROL") || str.Left(8) == _T("GROUPBOX") )
        {
            // needed only 2 commas (outside the '\"')
            if ( GetCommasCount(str) < 3 )
                str+=*((*init)+1);

            // the first thing after LTEXT(and other) is the caption
            CString strText;
            bool bControl = false;

            if (str.Left(5) == _T("LTEXT") || str.Left(5) == _T("CTEXT") || str.Left(5) == _T("RTEXT"))
                str=str.Mid(5);
            else if (str.Left(13) == _T("DEFPUSHBUTTON"))
                str=str.Mid(13);
            else if (str.Left(10) == _T("PUSHBUTTON"))
                str=str.Mid(10);
            else if (str.Left(7) == _T("CONTROL"))
            {
                bControl = true;
                str=str.Mid(7);
            }
            else if (str.Left(8) == _T("GROUPBOX"))
                str=str.Mid(8);

            str=str.Mid(str.Find(_T("\""))+1);
            int iPos=str.Find(_T("\""), 0);
            if (iPos != -1)
                strText=str.Left(iPos);
            else
                THROW(_T("Error: cannot find a comma in processed text"), 0, 0, 0);

            str = str.Mid(iPos+1);

            // after the first comma there is an ID
            iPos=str.Find(_T(","), 0);
            CString strID;
            if (iPos != -1)
            {
                str=str.Mid(iPos+1);
                iPos=str.Find(_T(","), 0);
                if (iPos != -1)
                    strID=str.Left(iPos);
                else
                    THROW(_T("Error: cannot find a comma in processed text"), 0, 0, 0);

                strID.TrimLeft(_T(" \t"));
                strID.TrimRight(_T(" \t"));
            }
            else
                THROW(_T("Error: cannot find a comma in processed text"), 0, 0, 0);

            bool bSkip = false;
            if(bControl)
            {
                str = str.Mid(iPos+1);
                iPos = str.Find(_T(","), 0);
                if(iPos == -1)
                    THROW(_T("Error: cannot find a comma in processed text"), 0, 0, 0);

                CString strType = str.Left(iPos);
                strType.Trim(_T("\""));
                if(strType == _T("SysListView32") || strType == _T("msctls_progress32") ||
                        strType == _T("ComboBoxEx32") || strType == _T("msctls_updown32") ||
                        strType == _T("SysDateTimePick32"))
                {
                    bSkip = true;
                }
            }

            if(!bSkip)
            {
                // find id
                UINT uiID = GetResourceID(strID);
                CString out;
                pElementMap->insert(std::make_pair(uiID, strText));
            }

            // now add the data to output rc
            str=**init;
            str.Replace(_T("\"")+strText+_T("\""), _T("\"\""));

            m_vOutRCFile.push_back(str);
        }
        else
            m_vOutRCFile.push_back(**init);
    }
}
Example #18
0
int CFunGSMTest_CMW::IGSMTestStartTxMeasurment(int BurstQty,int loopi,CStringVtr &strResult,CString strTestItem,int iEdge)
{
	CString strCmd;
	int iDeviceErr,iQueryTimes=50;
	CString strRes;
	CStringVtr strvRes;
	DblVtr dvStr;
	int iRes=0;
	CString strtemp;
	CStringVtr strVtrtemp;
	strtemp.Empty();
	strVtrtemp.clear();

	strCmd.Format("CONFigure:GSM:MEAS:MEValuation:RESult:PERRor ON");
	DEVICE_WRITE(strCmd)
		strCmd.Format("CONFigure:GSM:MEAS:MEValuation:RESult:EVM ON");
	DEVICE_WRITE(strCmd)
		strCmd.Format("CONFigure:GSM:MEAS:MEValuation:RESult:MERRor ON");
	DEVICE_WRITE(strCmd)
		strCmd.Format("CONFigure:GSM:MEAS:MEValuation:SCOunt:MODulation %d",BurstQty);
	DEVICE_WRITE(strCmd)
		strCmd.Format("CONFigure:GSM:MEAS:MEValuation:RESult:PVTime ON");
	DEVICE_WRITE(strCmd)
		strCmd.Format("CONFigure:GSM:MEAS:MEValuation:SCOunt:PVTime %d",BurstQty);
	DEVICE_WRITE(strCmd)
		strCmd.Format("CONFigure:GSM:MEAS:MEValuation:RESult:MSCalar ON");
	DEVICE_WRITE(strCmd)
		strCmd.Format("CONFigure:GSM:MEAS:MEValuation:SCOunt:MODulation %d",BurstQty);
	DEVICE_WRITE(strCmd)
		strCmd.Format("CONFigure:GSM:MEAS:MEValuation:RESult:SSFRequency ON");
	DEVICE_WRITE(strCmd)
		strCmd.Format("CONFigure:GSM:MEAS:MEValuation:SCOunt:SSWitching %d",BurstQty);
	DEVICE_WRITE(strCmd)
		strCmd.Format("CONFigure:GSM:MEAS:MEValuation:SSWitching:OFRequence 0.4e+6,0.6e+6,1.2e+6,1.8e+6,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF");
	DEVICE_WRITE(strCmd)
		strCmd.Format("CONFigure:GSM:MEAS:MEValuation:RESult:SMFRequency ON");
	DEVICE_WRITE(strCmd)
		strCmd.Format("CONFigure:GSM:MEAS:MEValuation:SCOunt:SMODulation %d",BurstQty);
	DEVICE_WRITE(strCmd)
		strCmd.Format("CONFigure:GSM:MEAS:MEValuation:SMODulation:OFRequence 0.1e+6,0.2e+6,0.25e+6,0.4e+6,0.6e+6,1e+6,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF,OFF");
	DEVICE_WRITE(strCmd)

		strCmd=_T("INITiate:GSM:MEAS:MEValuation");
	DEVICE_WRITE(strCmd);
	strCmd=_T("FETCh:GSM:MEAS:MEValuation:STATe?");
	do
	{
		Sleep(50);
		DEVICE_QUERY(strCmd)
			strRes=Device_GetReadBuf();

	}while((0!=strRes.Find("RDY"))&&(0<iQueryTimes--));
	if (0!=strRes.Find("RDY"))
	{
		return DEVICE_FINDRES_FAIL;
	}

	if (strTestItem.Find("A1")!=-1)
	{
		strVtrtemp.clear();
		strCmd=_T("FETCh:GSM:MEAS:MEValuation:PVTime:ALL?");
		DEVICE_QUERY(strCmd);
		strRes=Device_GetReadBuf();
		strRes.Replace("\r","");
		strRes.Replace("\n","");
		CStr::ParseString(strRes,_T(","),strVtrtemp);
		if (strVtrtemp[2].Find(_T("NCAP"))>-1)
		{
			return DEVICE_QUERY_FAIL;
		}
		strResult.push_back(strVtrtemp[2]);
	}
	if ((strTestItem.Find("B1")!=-1)||(strTestItem.Find("C1")!=-1)||(strTestItem.Find("D1")!=-1))
	{
		strVtrtemp.clear();
		strCmd=_T("FETCh:GSM:MEAS:MEValuation:MODulation:MAXimum?");
		DEVICE_QUERY(strCmd);
		strRes=Device_GetReadBuf();
		strRes.Replace("\r","");
		strRes.Replace("\n","");
		CStr::ParseString(strRes,_T(","),strVtrtemp);

		if(strTestItem.Find("B1")!=-1)
		{
			//MAX_PPHASEERR?");				
			strResult.push_back(strVtrtemp[7]);
		}
		
		strVtrtemp.clear();
		strCmd=_T("FETCh:GSM:MEAS:MEValuation:MODulation:AVERage?");
		DEVICE_QUERY(strCmd);
		strRes=Device_GetReadBuf();
		strRes.Replace("\r","");
		strRes.Replace("\n","");
		CStr::ParseString(strRes,_T(","),strVtrtemp);

		if (strTestItem.Find("C1")!=-1)
		{
			//AVG_PHASEERR?");
			strResult.push_back(strVtrtemp[6]);
		}
		if (strTestItem.Find("D1")!=-1)
		{
			//AVG_CARRFERR? HZ");
			strResult.push_back(strVtrtemp[10]);
		}

		
	}
	if (strTestItem.Find("E1")!=-1)
	{
		strVtrtemp.clear();
		strCmd=_T("FETCh:GSM:MEAS:MEValuation:PVTime:ALL?");
		DEVICE_QUERY(strCmd);
		strRes=Device_GetReadBuf();
		strRes.Replace("\r","");
		strRes.Replace("\n","");
		CStr::ParseString(strRes,_T(","),strVtrtemp);
		if (strVtrtemp[1].Find(_T("NCAP"))>-1)
		{
			return DEVICE_QUERY_FAIL;
		}
		double dOutTol=CStr::StrToFloat(strVtrtemp[1]);
		if(dOutTol>0)
		{strResult.push_back("FAIL");

		}
		else{strResult.push_back("PASS");}
		
	}
	if (strTestItem.Find("F1")!=-1)
	{		
		strCmd=_T("FETCh:GSM:MEAS:MEValuation:SSWitching?");
		DEVICE_QUERY(strCmd);
		strRes=Device_GetReadBuf();
		CStr::ParseString(strRes,_T(","),strVtrtemp);
		if (strVtrtemp[1].Find(_T("NCAP"))>-1)
		{
			return DEVICE_QUERY_FAIL;
		}
		double dOutTol=CStr::StrToFloat(strVtrtemp[1]);
		if(dOutTol>0)
		{strResult.push_back("FAIL");

		}
		else{strResult.push_back("PASS");}
	}

	if (strTestItem.Find("G1")!=-1)
	{
		strtemp.Empty();

		strCmd=_T("FETCh:GSM:MEAS:MEValuation:SSWitching:FREQuency?");
		DEVICE_QUERY(strCmd);
		strRes=Device_GetReadBuf();
		CStr::ParseString(strRes,",",strVtrtemp);
		strtemp=strVtrtemp[17]+","+strVtrtemp[18]+","+strVtrtemp[19]+","+strVtrtemp[20]+","+strVtrtemp[22]+","+strVtrtemp[23]+","+strVtrtemp[24]+","+strVtrtemp[25];
		strResult.push_back(strtemp);
	}
	if (strTestItem.Find("H1")!=-1)
	{		
		strCmd=_T("FETCh:GSM:MEAS:MEValuation:SMODulation?");
		DEVICE_QUERY(strCmd);
		strRes=Device_GetReadBuf();
		CStr::ParseString(strRes,_T(","),strVtrtemp);
		if (strVtrtemp[1].Find(_T("NCAP"))>-1)
		{
			return DEVICE_QUERY_FAIL;
		}
		double dOutTol=CStr::StrToFloat(strVtrtemp[1]);
		if(dOutTol>0)
		{strResult.push_back("FAIL");

		}
		else{strResult.push_back("PASS");}
	}

	if (strTestItem.Find("I1")!=-1)
	{
		strtemp.Empty();

		strCmd=_T("FETCh:GSM:MEAS:MEValuation:SMODulation:FREQuency?");
		DEVICE_QUERY(strCmd);
		strRes=Device_GetReadBuf();
		CStr::ParseString(strRes,",",strVtrtemp);
		strtemp=strVtrtemp[15]+","+strVtrtemp[16]+","+strVtrtemp[17]+","+strVtrtemp[18]+","+strVtrtemp[19]+","+strVtrtemp[20]+","+strVtrtemp[22]+","+strVtrtemp[23]+","+strVtrtemp[24]+","+strVtrtemp[25]+","+strVtrtemp[26]+","+strVtrtemp[27];
		strResult.push_back(strtemp);
	}
	

	return DEVICE_SUCCESS;
}
bool CloneCommand::Execute()
{
	CCloneDlg dlg;
	dlg.m_Directory=this->orgCmdLinePath.GetWinPathString();

	if (parser.HasKey(_T("url")))
		dlg.m_URL = parser.GetVal(_T("url"));

	if(dlg.DoModal()==IDOK)
	{
		CString recursiveStr;
		if(dlg.m_bRecursive)
			recursiveStr = _T("--recursive");
		else
			recursiveStr = _T("");

		CString bareStr;
		if(dlg.m_bBare)
			bareStr = _T("--bare");
		else
			bareStr = _T("");

		if(dlg.m_bAutoloadPuttyKeyFile)
		{
			CAppUtils::LaunchPAgent(&dlg.m_strPuttyKeyFile);
		}

		CAppUtils::RemoveTrailSlash(dlg.m_Directory);
		CAppUtils::RemoveTrailSlash(dlg.m_URL);

		CString dir=dlg.m_Directory;
		CString url=dlg.m_URL;

		// is this a windows format UNC path, ie starts with \\?
		if (url.Find(_T("\\\\")) == 0)
		{
			// yes, change all \ to /
			// this should not be necessary but msysgit does not support the use \ here yet
			int atSign = url.Find(_T('@'));
			if (atSign > 0)
			{
				CString path = url.Mid(atSign);
				path.Replace(_T('\\'), _T('/'));
				url = url.Mid(0, atSign) + path;
			}
			else
				url.Replace( _T('\\'), _T('/'));
		}

		CString depth;
		if (dlg.m_bDepth)
		{
			depth.Format(_T(" --depth %d"),dlg.m_nDepth);
		}

		g_Git.m_CurrentDir = this->orgCmdLinePath.GetWinPathString();

		CString cmd;
		CString progressarg;

		int ver = CAppUtils::GetMsysgitVersion();

		if(ver >= 0x01070002) //above 1.7.0.2
			progressarg = _T("--progress");

		cmd.Format(_T("git.exe clone %s %s %s -v %s \"%s\" \"%s\""),
						recursiveStr,
						bareStr,
						progressarg,
						depth,
						url,
						dir);

		// Handle Git SVN-clone
		if(dlg.m_bSVN)
		{
			//g_Git.m_CurrentDir=dlg.m_Directory;
			cmd.Format(_T("git.exe svn clone \"%s\"  \"%s\""),
				url,dlg.m_Directory);

			if(dlg.m_bSVNTrunk)
				cmd+=_T(" -T ")+dlg.m_strSVNTrunk;

			if(dlg.m_bSVNBranch)
				cmd+=_T(" -b ")+dlg.m_strSVNBranchs;

			if(dlg.m_bSVNTags)
				cmd+=_T(" -t ")+dlg.m_strSVNTags;

			if(dlg.m_bSVNFrom)
			{
				CString str;
				str.Format(_T("%d:HEAD"),dlg.m_nSVNFrom);
				cmd+=_T(" -r ")+str;
			}

			if(dlg.m_bSVNUserName)
			{
				cmd+= _T(" --username ");
				cmd+=dlg.m_strUserName;
			}
		}
		CProgressDlg progress;
		progress.m_GitCmd=cmd;
		INT_PTR ret = progress.DoModal();

		if( progress.m_GitStatus == 0)
		{
			if(dlg.m_bAutoloadPuttyKeyFile)
			{
				g_Git.m_CurrentDir = dlg.m_Directory;
				SetCurrentDirectory(g_Git.m_CurrentDir);

				if(g_Git.SetConfigValue(_T("remote.origin.puttykeyfile"), dlg.m_strPuttyKeyFile, CONFIG_LOCAL, CP_UTF8, &dlg.m_Directory))
				{
					CMessageBox::Show(NULL,_T("Fail set config remote.origin.puttykeyfile"),_T("TortoiseGit"),MB_OK|MB_ICONERROR);
					return FALSE;
				}
			}
		}
		if(ret == IDOK)
			return TRUE;

	}
	return FALSE;
}
Example #20
0
void CObjParser::ObjDataParser(CString sObjLineData)
{
	int pos = 0;
	CString sMQOTokenData, sChkTokenData;

	sObjLineData.Replace(_T("\r"), _T(""));
	sObjLineData.Replace(_T("\t"), _T(""));

	switch(g_nFileType)
	{
	case _MQO:
		sChkTokenData = sObjLineData;

		sMQOTokenData = sChkTokenData.Tokenize(_T(" "), pos);

		if(sMQOTokenData == _T("vertex"))	// vertex
		{
			g_blnVertexFlag = TRUE;
		}
		else if(sMQOTokenData == _T("face"))	// face
		{
			g_blnFaceFlag = TRUE;
		}
		else if(sMQOTokenData == _T("Material"))
		{
			g_blnTextureFlag = TRUE;
		}
		else if(sMQOTokenData == _T("}"))
		{
			g_blnVertexFlag = FALSE;
			g_blnFaceFlag = FALSE;
			g_blnTextureFlag = FALSE;
		}
		else if(g_blnVertexFlag == TRUE)	// vertex
		{
			Msg_OBJ_v_Parser(sObjLineData);
		}
		else if(g_blnFaceFlag == TRUE)		// face
		{
			Msg_MQO_face_Parser(sObjLineData);
		}
		else if(g_blnTextureFlag == TRUE)	// Texture
		{
			Msg_MQO_Load_Texture(sObjLineData);
		}
		break;
	
	case _NAVTEQOBJ:
	case _NORMALOBJ:
		if(sObjLineData.GetAt(0) == 'v')	
		{
			if(sObjLineData.GetAt(1) == 'n')		// vn : normal vertex
			{
				Msg_OBJ_vn_Parser(sObjLineData);
			}
			else if(sObjLineData.GetAt(1) == 't')	// vt : texture
			{
				Msg_OBJ_vt_Parser(sObjLineData);
			}
			else if(sObjLineData.GetAt(1) == ' ')	// v : vertex
			{
				Msg_OBJ_v_Parser(sObjLineData);
			}
		}
		else if(sObjLineData.GetAt(0) == 'f')		// f : Index
		{
			Msg_OBJ_f_Parser(sObjLineData);
		}
		else if(sObjLineData.GetAt(0) == 'm')		// .mtl File Name
		{
			if(sObjLineData.GetAt(1) == 't' && sObjLineData.GetAt(2) == 'l' && sObjLineData.GetAt(3) == 'l' && 
				sObjLineData.GetAt(4) == 'i' && sObjLineData.GetAt(5) == 'b' )
			{
				ChkMtlFileName(sObjLineData);
			}
		}
		break;
	}
}
bool MachineInstaller::ShouldSilentInstall()
{
	// Figure out the package name from our own EXE name 
	wchar_t ourFile[MAX_PATH];
	HMODULE hMod = GetModuleHandle(NULL);
	GetModuleFileName(hMod, ourFile, _countof(ourFile));

	CString fullPath = CString(ourFile);
	CString pkgName = CString(ourFile + fullPath.ReverseFind(L'\\'));
	pkgName.Replace(L".exe", L"");
	
	wchar_t installFolder[MAX_PATH];

	// C:\Users\Username\AppData\Local\$pkgName\packages
	SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, installFolder);
	wcscat(installFolder, L"\\");
	wcscat(installFolder, pkgName);
	wcscat(installFolder, L"\\");
	wcscat(installFolder, L"packages");

	if (GetFileAttributes(installFolder) != INVALID_FILE_ATTRIBUTES) {
		return false;
	}

	// C:\Users\Username\AppData\Local\$pkgName\.dead (was machine-installed but user uninstalled)
	SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, installFolder);
	wcscat(installFolder, L"\\");
	wcscat(installFolder, pkgName);
	wcscat(installFolder, L"\\");
	wcscat(installFolder, L".dead");

	if (GetFileAttributes(installFolder) != INVALID_FILE_ATTRIBUTES) {
		return false;
	}

	// C:\ProgramData\$pkgName\$username\packages
	wchar_t username[512];
	DWORD unamesize = _countof(username);
	SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, installFolder);
	GetUserName(username, &unamesize);
	wcscat(installFolder, L"\\");
	wcscat(installFolder, pkgName);
	wcscat(installFolder, L"\\");
	wcscat(installFolder, username);
	wcscat(installFolder, L"\\");
	wcscat(installFolder, L"packages");

	if (GetFileAttributes(installFolder) != INVALID_FILE_ATTRIBUTES) {
		return false;
	}

	// C:\ProgramData\$pkgName\$username\.dead
	SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, installFolder);
	wcscat(installFolder, L"\\");
	wcscat(installFolder, pkgName);
	wcscat(installFolder, L"\\");
	wcscat(installFolder, username);
	wcscat(installFolder, L"\\");
	wcscat(installFolder, L".dead");

	if (GetFileAttributes(installFolder) != INVALID_FILE_ATTRIBUTES) {
		return false;
	}

	// None of these exist, we should install
	return true;
}
Example #22
0
BOOL CTortoiseProcApp::InitInstance()
{
	EnableCrashHandler();
	InitializeJumpList();
	CheckUpgrade();
	CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows));
	CMFCButton::EnableWindowsTheming();

	Gdiplus::GdiplusStartupInput gdiplusStartupInput;
	Gdiplus::GdiplusStartup(&m_gdiplusToken,&gdiplusStartupInput,NULL);

	if(!CheckMsysGitDir())
	{
		UINT ret = CMessageBox::Show(NULL,_T("MSysGit (http://code.google.com/p/msysgit/) not found."),
									_T("TortoiseGit"), 3, IDI_HAND, _T("&Set MSysGit path"), _T("&Goto WebSite"), _T("&Abort"));
		if(ret == 2)
		{
			ShellExecute(NULL, NULL, _T("http://code.google.com/p/msysgit/"), NULL, NULL, SW_SHOW);
		}
		else if(ret == 1)
		{
			// open settings dialog
			CSettings dlg(IDS_PROC_SETTINGS_TITLE);
			dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
			dlg.SetTreeWidth(220);

			dlg.DoModal();
			dlg.HandleRestart();
		}
		return FALSE;
	}

	//set the resource dll for the required language
	CRegDWORD loc = CRegDWORD(_T("Software\\TortoiseGit\\LanguageID"), 1033);
	long langId = loc;
	CString langDll;
	CStringA langpath = CStringA(CPathUtils::GetAppParentDirectory());
	langpath += "Languages";
//	bindtextdomain("subversion", (LPCSTR)langpath);
//	bind_textdomain_codeset("subversion", "UTF-8");
	HINSTANCE hInst = NULL;
	do
	{
		langDll.Format(_T("..\\Languages\\TortoiseProc%d.dll"), langId);

		hInst = LoadLibrary(langDll);

		CString sVer = _T(STRPRODUCTVER);
		CString sFileVer = CPathUtils::GetVersionFromFile(langDll);
		if (sFileVer.Compare(sVer)!=0)
		{
			FreeLibrary(hInst);
			hInst = NULL;
		}
		if (hInst != NULL)
		{
			AfxSetResourceHandle(hInst);
		}
		else
		{
			DWORD lid = SUBLANGID(langId);
			lid--;
			if (lid > 0)
			{
				langId = MAKELANGID(PRIMARYLANGID(langId), lid);
			}
			else
				langId = 0;
		}
	} while ((hInst == NULL) && (langId != 0));
	TCHAR buf[6];
	_tcscpy_s(buf, _T("en"));
	langId = loc;
	CString sHelppath;
	sHelppath = this->m_pszHelpFilePath;
	sHelppath = sHelppath.MakeLower();
	// MFC uses a help file with the same name as the application by default,
	// which means we have to change that default to our language specific help files
	sHelppath.Replace(_T("tortoiseproc.chm"), _T("TortoiseGit_en.chm"));
	free((void*)m_pszHelpFilePath);
	m_pszHelpFilePath=_tcsdup(sHelppath);
	sHelppath = CPathUtils::GetAppParentDirectory() + _T("Languages\\TortoiseGit_en.chm");
	do
	{
		CString sLang = _T("_");
		if (GetLocaleInfo(MAKELCID(langId, SORT_DEFAULT), LOCALE_SISO639LANGNAME, buf, _countof(buf)))
		{
			sLang += buf;
			sHelppath.Replace(_T("_en"), sLang);
			if (PathFileExists(sHelppath))
			{
				free((void*)m_pszHelpFilePath);
				m_pszHelpFilePath=_tcsdup(sHelppath);
				break;
			}
		}
		sHelppath.Replace(sLang, _T("_en"));
		if (GetLocaleInfo(MAKELCID(langId, SORT_DEFAULT), LOCALE_SISO3166CTRYNAME, buf, _countof(buf)))
		{
			sLang += _T("_");
			sLang += buf;
			sHelppath.Replace(_T("_en"), sLang);
			if (PathFileExists(sHelppath))
			{
				free((void*)m_pszHelpFilePath);
				m_pszHelpFilePath=_tcsdup(sHelppath);
				break;
			}
		}
		sHelppath.Replace(sLang, _T("_en"));

		DWORD lid = SUBLANGID(langId);
		lid--;
		if (lid > 0)
		{
			langId = MAKELANGID(PRIMARYLANGID(langId), lid);
		}
		else
			langId = 0;
	} while (langId);
	setlocale(LC_ALL, "");

	// InitCommonControls() is required on Windows XP if an application
	// manifest specifies use of ComCtl32.dll version 6 or later to enable
	// visual styles.  Otherwise, any window creation will fail.

	INITCOMMONCONTROLSEX used = {
		sizeof(INITCOMMONCONTROLSEX),
			ICC_ANIMATE_CLASS | ICC_BAR_CLASSES | ICC_COOL_CLASSES | ICC_DATE_CLASSES |
			ICC_HOTKEY_CLASS | ICC_INTERNET_CLASSES | ICC_LISTVIEW_CLASSES |
			ICC_NATIVEFNTCTL_CLASS | ICC_PAGESCROLLER_CLASS | ICC_PROGRESS_CLASS |
			ICC_TAB_CLASSES | ICC_TREEVIEW_CLASSES | ICC_UPDOWN_CLASS |
			ICC_USEREX_CLASSES | ICC_WIN95_CLASSES
	};
	InitCommonControlsEx(&used);
	AfxOleInit();
	AfxEnableControlContainer();
	AfxInitRichEdit2();
	CWinAppEx::InitInstance();
	SetRegistryKey(_T("TortoiseGit"));

	CCmdLineParser parser(AfxGetApp()->m_lpCmdLine);

	// if HKCU\Software\TortoiseGit\Debug is not 0, show our command line
	// in a message box
	if (CRegDWORD(_T("Software\\TortoiseGit\\Debug"), FALSE)==TRUE)
		AfxMessageBox(AfxGetApp()->m_lpCmdLine, MB_OK | MB_ICONINFORMATION);

	if ( parser.HasKey(_T("path")) && parser.HasKey(_T("pathfile")))
	{
		CMessageBox::Show(NULL, IDS_ERR_INVALIDPATH, IDS_APPNAME, MB_ICONERROR);
		return FALSE;
	}

	CTGitPath cmdLinePath;
	CTGitPathList pathList;
	if ( parser.HasKey(_T("pathfile")) )
	{

		CString sPathfileArgument = CPathUtils::GetLongPathname(parser.GetVal(_T("pathfile")));

		cmdLinePath.SetFromUnknown(sPathfileArgument);
		if (pathList.LoadFromFile(cmdLinePath)==false)
			return FALSE;		// no path specified!
		if ( parser.HasKey(_T("deletepathfile")) )
		{
			// We can delete the temporary path file, now that we've loaded it
			::DeleteFile(cmdLinePath.GetWinPath());
		}
		// This was a path to a temporary file - it's got no meaning now, and
		// anybody who uses it again is in for a problem...
		cmdLinePath.Reset();

	}
	else
	{

		CString sPathArgument = CPathUtils::GetLongPathname(parser.GetVal(_T("path")));
		int asterisk = sPathArgument.Find('*');
		cmdLinePath.SetFromUnknown(asterisk >= 0 ? sPathArgument.Left(asterisk) : sPathArgument);
		pathList.LoadFromAsteriskSeparatedString(sPathArgument);
	}

	if (pathList.GetCount() == 0) {
		pathList.AddPath(CTGitPath::CTGitPath(g_Git.m_CurrentDir));
	}

	hWndExplorer = NULL;
	CString sVal = parser.GetVal(_T("hwnd"));
	if (!sVal.IsEmpty())
		hWndExplorer = (HWND)_ttoi64(sVal);

	while (GetParent(hWndExplorer)!=NULL)
		hWndExplorer = GetParent(hWndExplorer);
	if (!IsWindow(hWndExplorer))
	{
		hWndExplorer = NULL;
	}

	// Subversion sometimes writes temp files to the current directory!
	// Since TSVN doesn't need a specific CWD anyway, we just set it
	// to the users temp folder: that way, Subversion is guaranteed to
	// have write access to the CWD
	{
		DWORD len = GetCurrentDirectory(0, NULL);
		if (len)
		{
			TCHAR * originalCurrentDirectory = new TCHAR[len];
			if (GetCurrentDirectory(len, originalCurrentDirectory))
			{
				//sOrigCWD = originalCurrentDirectory;
				//sOrigCWD = CPathUtils::GetLongPathname(sOrigCWD);
			}
			delete [] originalCurrentDirectory;
		}
		TCHAR pathbuf[MAX_PATH];
		GetTempPath(MAX_PATH, pathbuf);
		SetCurrentDirectory(pathbuf);
	}

	// check for newer versions
	if (CRegDWORD(_T("Software\\TortoiseGit\\CheckNewer"), TRUE) != FALSE)
	{
		time_t now;
		struct tm ptm;

		time(&now);
		if ((now != 0) && (localtime_s(&ptm, &now)==0))
		{
			int week = 0;
			// we don't calculate the real 'week of the year' here
			// because just to decide if we should check for an update
			// that's not needed.
			week = ptm.tm_yday / 7;

			CRegDWORD oldweek = CRegDWORD(_T("Software\\TortoiseGit\\CheckNewerWeek"), (DWORD)-1);
			if (((DWORD)oldweek) == -1)
				oldweek = week;		// first start of TortoiseProc, no update check needed
			else
			{
				if ((DWORD)week != oldweek)
				{
					oldweek = week;

					TCHAR com[MAX_PATH+100];
					GetModuleFileName(NULL, com, MAX_PATH);
					_tcscat_s(com, MAX_PATH+100, _T(" /command:updatecheck"));

					CAppUtils::LaunchApplication(com, 0, false);
				}
			}
		}
	}

	if (parser.HasVal(_T("configdir")))
	{
		// the user can override the location of the Subversion config directory here
		CString sConfigDir = parser.GetVal(_T("configdir"));
//		g_GitGlobal.SetConfigDir(sConfigDir);
	}
	// to avoid that SASL will look for and load its plugin dlls all around the
	// system, we set the path here.
	// Note that SASL doesn't have to be initialized yet for this to work
//	sasl_set_path(SASL_PATH_TYPE_PLUGIN, (LPSTR)(LPCSTR)CUnicodeUtils::GetUTF8(CPathUtils::GetAppDirectory().TrimRight('\\')));

	HANDLE TSVNMutex = ::CreateMutex(NULL, FALSE, _T("TortoiseGitProc.exe"));
	if(!g_Git.SetCurrentDir(cmdLinePath.GetWinPathString()))
	{
		int i=0;
		for(i=0;i<pathList.GetCount();i++)
			if(g_Git.SetCurrentDir(pathList[i].GetWinPath()))
				break;
	}

	if(!g_Git.m_CurrentDir.IsEmpty())
		SetCurrentDirectory(g_Git.m_CurrentDir);

	{
		CString err;
		try
		{
			// requires CWD to be set
			CGit::m_LogEncode = CAppUtils::GetLogOutputEncode();
		}
		catch (char* msg)
		{
			err = CString(msg);
		}

		if (!err.IsEmpty())
		{
			UINT choice = CMessageBox::Show(hWndExplorer, err, _T("TortoiseGit Error"), 1, IDI_ERROR, _T("&Edit .git/config"), _T("Edit &global .gitconfig"), _T("&Abort"));
			if (choice == 1)
			{
				// open the config file with alternative editor
				CString path = g_Git.m_CurrentDir;
				path += _T("\\.git\\config");
				CAppUtils::LaunchAlternativeEditor(path);
			}
			else if (choice == 2)
			{
				// open the global config file with alternative editor
				TCHAR buf[MAX_PATH];
				ExpandEnvironmentStrings(_T("%HOMEDRIVE%\\%HOMEPATH%\\.gitconfig"), buf, MAX_PATH);
				CAppUtils::LaunchAlternativeEditor(buf);
			}
			return FALSE;
		}
	}

	// execute the requested command
	CommandServer server;
	Command * cmd = server.GetCommand(parser.GetVal(_T("command")));
	if (cmd)
	{
		cmd->SetExplorerHwnd(hWndExplorer);

		cmd->SetParser(parser);
		cmd->SetPaths(pathList, cmdLinePath);

		retSuccess = cmd->Execute();
		delete cmd;
	}

	if (TSVNMutex)
		::CloseHandle(TSVNMutex);

	// Look for temporary files left around by TortoiseSVN and
	// remove them. But only delete 'old' files because some
	// apps might still be needing the recent ones.
	{
		DWORD len = ::GetTempPath(0, NULL);
		TCHAR * path = new TCHAR[len + 100];
		len = ::GetTempPath (len+100, path);
		if (len != 0)
		{
			CSimpleFileFind finder = CSimpleFileFind(path, _T("*svn*.*"));
			FILETIME systime_;
			::GetSystemTimeAsFileTime(&systime_);
			__int64 systime = (((_int64)systime_.dwHighDateTime)<<32) | ((__int64)systime_.dwLowDateTime);
			while (finder.FindNextFileNoDirectories())
			{
				CString filepath = finder.GetFilePath();
				HANDLE hFile = ::CreateFile(filepath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
				if (hFile != INVALID_HANDLE_VALUE)
				{
					FILETIME createtime_;
					if (::GetFileTime(hFile, &createtime_, NULL, NULL))
					{
						::CloseHandle(hFile);
						__int64 createtime = (((_int64)createtime_.dwHighDateTime)<<32) | ((__int64)createtime_.dwLowDateTime);
						if ((createtime + 864000000000) < systime)		//only delete files older than a day
						{
							::SetFileAttributes(filepath, FILE_ATTRIBUTE_NORMAL);
							::DeleteFile(filepath);
						}
					}
					else
						::CloseHandle(hFile);
				}
			}
		}
		delete[] path;
	}

	// Since the dialog has been closed, return FALSE so that we exit the
	// application, rather than start the application's message pump.
	return FALSE;
}
Example #23
0
int CSmtpClient::SendEmailToRecipient(CString sSmtpServer, CEmailMessage* msg)
{
	// This method connects to the given SMTP server and tries to send
	// the E-mail message.

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

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

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

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

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

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

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

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

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

		// Close socket
        closesocket(sock);
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

    /* Message text */

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

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

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

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

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

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

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

        delete [] buf;
    }

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

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

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

    // OK.
    status = 0;

exit:

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

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

    // Clean up
    closesocket(sock);
    freeaddrinfo(result);  
    return status;
}
Example #24
0
bool CCollection::InitCollectionFromFile(const CString& sFilePath, CString sFileName)
{
	DEBUG_ONLY( sFileName.Replace(COLLECTION_FILEEXTENSION, _T("")) );

	bool bCollectionLoaded = false;

	CSafeFile data;
	if(data.Open(sFilePath, CFile::modeRead | CFile::shareDenyWrite | CFile::typeBinary))
	{
		try
		{
			uint32 nVersion = data.ReadUInt32();
			if(nVersion == COLLECTION_FILE_VERSION1_INITIAL || nVersion == COLLECTION_FILE_VERSION2_LARGEFILES)
			{
				uint32 headerTagCount = data.ReadUInt32();
				while(headerTagCount)
				{
					CTag tag(&data, true);
					switch(tag.GetNameID())
					{
						case FT_FILENAME:
						{
							if(tag.IsStr())
								m_sCollectionName = tag.GetStr();
							break;
						}
						case FT_COLLECTIONAUTHOR:
						{
							if(tag.IsStr())
								m_sCollectionAuthorName = tag.GetStr();
							break;
						}
						case FT_COLLECTIONAUTHORKEY:
						{
							if(tag.IsBlob())
							{
								SetCollectionAuthorKey(tag.GetBlob(), tag.GetBlobSize());
							}
							break;
						}
					}
					headerTagCount--;
				}
				uint32 fileCount = data.ReadUInt32();
				while(fileCount)
				{
					CCollectionFile* pCollectionFile = new CCollectionFile(&data);
					if(pCollectionFile)
						AddFileToCollection(pCollectionFile, false);
					fileCount--;
				}
				bCollectionLoaded = true;
			}
			if (m_pabyCollectionAuthorKey != NULL){
					bool bResult = false;
					if (data.GetLength() > data.GetPosition()){
						using namespace CryptoPP;

						uint32 nPos = (uint32)data.GetPosition();
						data.SeekToBegin();
						BYTE* pMessage = new BYTE[nPos];
						VERIFY( data.Read(pMessage, nPos) == nPos);

						StringSource ss_Pubkey(m_pabyCollectionAuthorKey, m_nKeySize, true, 0);
						RSASSA_PKCS1v15_SHA_Verifier pubkey(ss_Pubkey);
		
						int nSignLen = (int)(data.GetLength() - data.GetPosition());
						BYTE* pSignature = new BYTE[nSignLen ];
						VERIFY( data.Read(pSignature, nSignLen) == (UINT)nSignLen);

						bResult = pubkey.VerifyMessage(pMessage, nPos, pSignature, nSignLen);

						delete[] pMessage;
						delete[] pSignature;
					}	
					if (!bResult){
						DebugLogWarning(_T("Collection %s: Verifying of public key failed!"), m_sCollectionName);
						delete[] m_pabyCollectionAuthorKey;
						m_pabyCollectionAuthorKey = NULL;
						m_nKeySize = 0;
						m_sCollectionAuthorName = _T("");
					}
					else
						DebugLog(_T("Collection %s: Public key verified"), m_sCollectionName);
					
			}
			else
				m_sCollectionAuthorName = _T("");
			data.Close();
		}
		catch(CFileException* error)
		{
			error->Delete();
			return false;
		}
		catch(...)
		{
			ASSERT( false );
			data.Close();
			return false;
		}
	}
	else
		return false;

	if(!bCollectionLoaded)
	{
		CStdioFile data;
		if(data.Open(sFilePath, CFile::modeRead | CFile::shareDenyWrite | CFile::typeText))
		{
			try
			{
				CString sLink;
				while(data.ReadString(sLink))
				{
					//Ignore all lines that start with #.
					//These lines can be used for future features..
					if(sLink.Find(_T("#")) != 0)
					{
						try
						{
							CCollectionFile* pCollectionFile = new CCollectionFile();
							if (pCollectionFile->InitFromLink(sLink))
								AddFileToCollection(pCollectionFile, false);
							else
								delete pCollectionFile;
						}
						catch(...)
						{
							ASSERT( false );
							data.Close();
							return false;
						}
					}
				}
				data.Close();
				m_sCollectionName = sFileName;
				bCollectionLoaded = true;
				m_bTextFormat = true;
			}
			catch(CFileException* error)
			{
				error->Delete();
				return false;
			}
			catch(...)
			{
				ASSERT( false );
				data.Close();
				return false;
			}
		}
	}

	return bCollectionLoaded;
}
Example #25
0
void CStatistic::ReplacePlaceholders( CString & szUrl, const CString & szType, const CString & szAction )
{
    if (szUrl.IsEmpty())
    {
        ATLASSERT(FALSE);
        return;
    }

    if (m_szPID.IsEmpty())
    {
        m_szPID = GetPID();
    }

    if (m_szMID.IsEmpty())
    {
        GetMID(m_szMID.GetBufferSetLength(MAX_PATH), MAX_PATH);
    }

    if (m_szAppVer.IsEmpty())
    {
        WCHAR szFile[MAX_PATH] = {};
        GetModuleFileName(g_hModule, szFile, MAX_PATH);
        PathRemoveFileSpec(szFile);
        PathRemoveFileSpec(szFile);
        PathAppend(szFile, APP_NAME);

        GetFileVer(szFile, m_szAppVer.GetBufferSetLength(MAX_PATH), MAX_PATH);
    }

    if (m_szModVer.IsEmpty())
    {
        WCHAR szFile[MAX_PATH] = {};
        GetModuleFileName(g_hModule, szFile, MAX_PATH);

        GetFileVer(szFile, m_szModVer.GetBufferSetLength(MAX_PATH), MAX_PATH);
    }

    if (szUrl.Find(URL_PID) > 0)
    {
        szUrl.Replace(URL_PID, m_szPID);
    }

    if (szUrl.Find(URL_MID) > 0)
    {
        szUrl.Replace(URL_MID, m_szMID);
    }

    if (szUrl.Find(URL_APP_VER) > 0)
    {
        szUrl.Replace(URL_APP_VER, m_szAppVer);
    }

    if (szUrl.Find(URL_MOD_VER) > 0)
    {
        szUrl.Replace(URL_MOD_VER, m_szModVer);
    }

    if (szUrl.Find(URL_TYPE) > 0)
    {
        szUrl.Replace(URL_TYPE, szType);
    }

    if (szUrl.Find(URL_ACTION) > 0)
    {
        szUrl.Replace(URL_ACTION, szAction);
    }
}
Example #26
0
int CPlayerMgr::StartPlayer(const uchar * filehash, CString strFilename, UINT64 uFileSize, CString strExt)
{
	if(! g_PlayerMgr)
	{
		g_hNotifyWnd = AfxGetMainWnd()->GetSafeHwnd();
		g_PlayerMgr = (CPlayerMgr*)AfxBeginThread(RUNTIME_CLASS(CPlayerMgr));

		//  开始成功端口侦听
		while(g_PlayerMgr->GetListenPort()==0)
		{
			Sleep(100);
		}
	}

	if(strExt.IsEmpty() || filehash==NULL)
		return 1;

	CSKey key(filehash);

	CSingleLock lock(&CPlayerMgr::m_Mutex, true);

	TCHAR szBuf[_MAX_PATH], szBuf2[_MAX_PATH];
	ULONG ulSize = _MAX_PATH;

	CString strExeFile;
	CRegKey reg;
	if(reg.Open(HKEY_CLASSES_ROOT, _T(".")+strExt)==ERROR_SUCCESS)
	{
		if(reg.QueryStringValue(NULL, szBuf, &ulSize)==ERROR_SUCCESS)
		{
			CString strCmd;
			strCmd.Format(_T("%s\\shell"), szBuf);
			if(reg.Open(HKEY_CLASSES_ROOT, strCmd)==ERROR_SUCCESS)
			{
				ulSize = _MAX_PATH;
				if(reg.QueryStringValue(NULL, szBuf2, &ulSize)==ERROR_SUCCESS)
				{
					strCmd.Format(_T("%s\\shell\\%s\\command"), szBuf, szBuf2);
					if(reg.Open(HKEY_CLASSES_ROOT, strCmd)==ERROR_SUCCESS)
					{
						ulSize = _MAX_PATH;
						if(reg.QueryStringValue(NULL, szBuf, &ulSize)==ERROR_SUCCESS)
						{
							strExeFile = szBuf;
						}
					}
				}
			}
		}
	}

	//  使用配置的播放器
	if(strExeFile.IsEmpty())
	{
		// todo
		return 2;
	}

	CString strCmdLine;
	DWORD * pKey=(DWORD*)key.m_key;
	strCmdLine.Format(_T("\"http://127.0.0.1:%d/%08x%08x%08x%08x/%s\""), g_PlayerMgr->GetListenPort(),
		pKey[0], pKey[1], pKey[2], pKey[3], strFilename);

	strExeFile.Replace(_T("\"%1\""), _T(""));
	strExeFile.Replace(_T("%1"), _T(""));
	strExeFile.Trim();

	//  把参数剥出来
	int nParamPos;
	CString strTmp = strExeFile;
	while((nParamPos = strTmp.ReverseFind(_T('.'))) >= 0)
	{
		LPCTSTR szExe = strTmp;
		if(_tcsnicmp(szExe + nParamPos, _T(".exe"), 4)==0)
		{
			nParamPos += 4;
			break;
		}
		else
		{
			strTmp = strTmp.Left(nParamPos);
		}
	}

	if(nParamPos==-1)
	{
		return 2;
	}

	CString strExeParam;
	if(nParamPos<strExeFile.GetLength()-1)
	{
		if(strExeFile.GetAt(nParamPos)==_T('\"'))
			nParamPos++;

		strExeParam = strExeFile.Mid(nParamPos);
		strExeFile = strExeFile.Left(nParamPos);
	}

	CPlayerTask * pTask = g_PlayerMgr->AddPlayerTask(key);
	pTask->m_uTotalFileSize = uFileSize;
//	CStringA strTmpA;
//	strTmpA.Format(httphead, dwFileSize);
//	pTask->SendData((void*)(const char*)strTmpA, strTmpA.GetLength());

	//if(! pTask->m_fileToRead.Duplicate() Open(strFilepath, CFile::modeRead|CFile::shareDenyWrite))
	//{
	//	g_PlayerMgr->RemovePlayerTask(key);
	//	return 3;
	//}

	ShellExecute(NULL,_T("open"), strExeFile, strCmdLine + strExeParam, NULL, SW_SHOW);
	return 0;
}
Example #27
0
//
// OpenFile
//
// Opens the file ready for streaming
//
HRESULT FileReader::OpenFile()
{
  CAutoLockFR rLock (&m_accessLock);
	WCHAR *pFileName = NULL;
	DWORD Tmo=14 ;
  HANDLE hFileUnbuff = INVALID_HANDLE_VALUE;
  
  //Can be used to open files in random-access mode to workaround SMB caching problems
  DWORD accessModeFlags = (m_bUseRandomAccess ? FILE_FLAG_RANDOM_ACCESS : FILE_FLAG_SEQUENTIAL_SCAN);     
  
	// Is the file already opened
	if (m_hFile != INVALID_HANDLE_VALUE) 
  {
    LogDebug("FileReader::OpenFile() file already open");
		return NOERROR;
	}

	// Has a filename been set yet
	if (m_pFileName == NULL) 
  {
    LogDebug("FileReader::OpenFile() no filename");
		return ERROR_INVALID_NAME;
	}
	
  m_bIsStopping = false;

	pFileName = m_pFileName;

  //LogDebug("FileReader::OpenFile(), Filename: %ws.", pFileName);

	do
	{
	  if (m_bIsStopping)
	    return E_FAIL;
	    
	  if (m_bUseDummyWrites)  //enable SMB2/SMB3 file existence cache workaround
	  {
  		if ((wcsstr(pFileName, L".ts.tsbuffer") != NULL)) //timeshift file only
  		{  	  
    	  CString tempFileName = pFileName;
    	  
    	  int replCount = tempFileName.Replace(L".ts.tsbuffer", randomStrGen(12));
  
        if (replCount > 0)
        {
    	    //LogDebug("FileReader::OpenFile(), try to write dummy file to update SMB2 cache - %ws", tempFileName);
      		hFileUnbuff = ::CreateFileW(tempFileName,		// The filename
      							(DWORD) (GENERIC_READ | GENERIC_WRITE),				// File access
      							(DWORD) (FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE), // Share access
      							NULL,						            // Security
      							(DWORD) CREATE_ALWAYS,		  // Open flags
      							(DWORD) (FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE),	// More flags
      							NULL);						          // Template
      
      		if (hFileUnbuff != INVALID_HANDLE_VALUE)
      		{
      		  char tempData[16] = {0x0,0x1,0x2,0x3,0x4,0x5,0x6,0x7,0x8,0x9,0xA,0xB,0xC,0xD,0xE,0xF};
      		  DWORD bytesWritten;
            ::WriteFile(hFileUnbuff, tempData, 16, &bytesWritten, NULL);  
          	::CloseHandle(hFileUnbuff); //File is deleted on CloseHandle since FILE_FLAG_DELETE_ON_CLOSE was used
          	hFileUnbuff = INVALID_HANDLE_VALUE; // Invalidate the file
    	      //LogDebug("FileReader::OpenFile(), dummy file write %d bytes to %ws", bytesWritten, tempFileName);
      		}
      	}
      }
    }
    
		// do not try to open a tsbuffer file without SHARE_WRITE so skip this try if we have a buffer file
		if (wcsstr(pFileName, L".ts.tsbuffer") == NULL)   // not tsbuffer files
		{
			// Try to open the file in read-only mode (should fail for 'live' recordings)
			m_hFile = ::CreateFileW(pFileName,      // The filename
						 (DWORD) GENERIC_READ,        // File access
						 (DWORD) FILE_SHARE_READ,     // Share access
						 NULL,                        // Security
						 (DWORD) OPEN_EXISTING,       // Open flags
						 (DWORD) accessModeFlags,     // More flags
						 NULL);                       // Template
			if (m_hFile != INVALID_HANDLE_VALUE) break ;
			  
  		//This is in case file is being recorded to ('live' recordings)
  		m_hFile = ::CreateFileW(pFileName,		// The filename
  							(DWORD) GENERIC_READ,				// File access
  							(DWORD) (FILE_SHARE_READ | FILE_SHARE_WRITE), // Share access
  							NULL,						            // Security
  							(DWORD) OPEN_EXISTING,		  // Open flags
  							(DWORD) accessModeFlags,	                // More flags
  							NULL);						          // Template 
  		if (m_hFile != INVALID_HANDLE_VALUE) break ;
		}
    else  //for tsbuffer files
    {
  		//This is in case file is being recorded to
  		m_hFile = ::CreateFileW(pFileName,		// The filename
  							(DWORD) GENERIC_READ,				// File access
  							(DWORD) (FILE_SHARE_READ | FILE_SHARE_WRITE), // Share access
  							NULL,						            // Security
  							(DWORD) OPEN_EXISTING,		  // Open flags
  							(DWORD) accessModeFlags,	  // More flags
  							NULL);						                // Template 
  		if (m_hFile != INVALID_HANDLE_VALUE) break ;
	  }

		if ((wcsstr(pFileName, L".ts.tsbuffer") != NULL) && (Tmo<10)) //timeshift file only
		{
  	  if (m_bUseDummyWrites)  //enable SMB2/SMB3 file existence cache workaround
  	  {
  		  //Not succeeded in opening file yet, try WRITE_THROUGH dummy file write
    	  CString tempFileName = pFileName;
    	  int replCount = tempFileName.Replace(L".ts.tsbuffer", randomStrGen(12));
  
        if (replCount > 0)
        {
    	    // LogDebug("FileReader::OpenFile(), try to write dummy file to update SMB2 cache - %ws", tempFileName);
      		hFileUnbuff = ::CreateFileW(tempFileName,		// The filename
      							(DWORD) (GENERIC_READ | GENERIC_WRITE),				// File access
      							(DWORD) (FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE), // Share access
      							NULL,						            // Security
      							(DWORD) CREATE_ALWAYS,		  // Open flags
      							(DWORD) (FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE | FILE_FLAG_WRITE_THROUGH),	// More flags
      							NULL);						          // Template
      
      		if (hFileUnbuff != INVALID_HANDLE_VALUE)
      		{
      		  char tempData[16] = {0x0,0x1,0x2,0x3,0x4,0x5,0x6,0x7,0x8,0x9,0xA,0xB,0xC,0xD,0xE,0xF};
      		  DWORD bytesWritten;
            ::WriteFile(hFileUnbuff, tempData, 16, &bytesWritten, NULL);  
            Sleep(50);   		  
          	::CloseHandle(hFileUnbuff); //File is deleted on CloseHandle since FILE_FLAG_DELETE_ON_CLOSE was used
          	hFileUnbuff = INVALID_HANDLE_VALUE; // Invalidate the file
    	      LogDebug("FileReader::OpenFile(), dummy file WRITE_THROUGH write %d bytes to %ws", bytesWritten, tempFileName);
      		}
      	}
      }

  		//No luck yet, so try unbuffered open and close (to flush SMB2 cache?),
  		//then go round loop again to open it properly (hopefully....)
  		hFileUnbuff = ::CreateFileW(pFileName,		// The filename
  							(DWORD) GENERIC_READ,				// File access
  							(DWORD) (FILE_SHARE_READ | FILE_SHARE_WRITE), // Share access
  							NULL,						            // Security
  							(DWORD) OPEN_EXISTING,		  // Open flags
  							(DWORD) FILE_FLAG_NO_BUFFERING,	// More flags
  							NULL);						          // Template
  
  		if (hFileUnbuff != INVALID_HANDLE_VALUE)
  		{
      	::CloseHandle(hFileUnbuff);
      	hFileUnbuff = INVALID_HANDLE_VALUE; // Invalidate the file
  		}
  	  //LogDebug("FileReader::OpenFile() unbuff, %d tries to open %ws", 15-Tmo, pFileName);  	  
    }

		Sleep(min((20*(15-Tmo)),250)) ; //wait longer between retries as loop iterations increase
	}
	while(--Tmo) ;
	
	if (Tmo)
	{
    if (Tmo<13) // 1 failed + 1 succeded is quasi-normal, more is a bit suspicious ( disk drive too slow or problem ? )
  			LogDebug("FileReader::OpenFile(), %d tries to succeed opening %ws.", 15-Tmo, pFileName);
	}
	else
	{
	  HRESULT lastErr = HRESULT_FROM_WIN32(GetLastError());	  
		LogDebug("FileReader::OpenFile(), open file failed. Error 0x%x, %ws, filename = %ws", lastErr, HresultToCString(lastErr), pFileName);    
		return E_FAIL;
	}

  //LogDebug("FileReader::OpenFile() handle %i %ws", m_hFile, pFileName );

	LARGE_INTEGER li;
	li.QuadPart = 0;
	::SetFilePointer(m_hFile, li.LowPart, &li.HighPart, FILE_BEGIN);

	return S_OK;

} // Open
Example #28
0
bool CGPImporter::ImportTask(const CXmlItem* pXISrcTask, ITaskList8* pDestTaskFile, HTASKITEM htDestParent, BOOL bAndSiblings)
{
	if (!pXISrcTask)
		return true;

	CString sName = pXISrcTask->GetItemValue(_T("name"));
	DWORD dwID = GetTDLTaskID(pXISrcTask->GetItemValueI(_T("id")));
	ASSERT(dwID);

	HTASKITEM hTask = pDestTaskFile->NewTask(sName, htDestParent, dwID);
	ASSERT (hTask);

	if (!hTask)
		return false;

	// completion
	int nPercentDone = pXISrcTask->GetItemValueI(_T("complete"));
	pDestTaskFile->SetTaskPercentDone(hTask, (unsigned char)nPercentDone);

	// dates
	time_t tStart;
	
	if (CDateHelper::DecodeDate(pXISrcTask->GetItemValue(_T("start")), tStart))
	{
		pDestTaskFile->SetTaskStartDate(hTask, tStart);

		int nDuration = pXISrcTask->GetItemValueI(_T("duration"));

		// only add duration to leaf tasks else it'll double up
		if (nDuration && !pXISrcTask->HasItem(_T("task")))
		{
			if (nPercentDone == 100)
			{
				pDestTaskFile->SetTaskDoneDate(hTask, tStart + (nDuration - 1) * ONEDAY); // gp dates are inclusive
				pDestTaskFile->SetTaskTimeSpent(hTask, nDuration, 'D');
			}
			else
			{
				pDestTaskFile->SetTaskDueDate(hTask, tStart + (nDuration - 1) * ONEDAY); // gp dates are inclusive
				pDestTaskFile->SetTaskTimeEstimate(hTask, nDuration, 'D');
			}
		}
	}

	// priority
	int nPriority = pXISrcTask->GetItemValueI(_T("priority"));
	pDestTaskFile->SetTaskPriority(hTask, (unsigned char)(nPriority * 3 + 2)); // 2, 5, 8

	// file ref
	CString sFileRef = pXISrcTask->GetItemValue(_T("webLink"));
	sFileRef.TrimLeft();

	if (!sFileRef.IsEmpty())
	{
		// decode file paths
		if (sFileRef.Find(_T("file://")) == 0)
		{
			sFileRef = sFileRef.Mid(7);
			sFileRef.Replace(_T("%20"), _T(""));
		}

		pDestTaskFile->SetTaskFileReferencePath(hTask, sFileRef);
	}

	// comments
	pDestTaskFile->SetTaskComments(hTask, pXISrcTask->GetItemValue(_T("notes")));

	// dependency
	// do this after we've imported all the tasks because GP does it 
	// the opposite way round to TDL

	// children
	if (!ImportTask(pXISrcTask->GetItem(_T("task")), pDestTaskFile, hTask, TRUE))
		return false;

	// handle sibling tasks WITHOUT RECURSION
	if (bAndSiblings)
	{
		pXISrcTask = pXISrcTask->GetSibling();
		
		while (pXISrcTask)
		{
			// FALSE == don't recurse on siblings
			if (!ImportTask(pXISrcTask, pDestTaskFile, htDestParent, FALSE))
				return false;
			
			pXISrcTask = pXISrcTask->GetSibling();
		}
	}
	
	return true;
}
Example #29
0
BOOL CCopyDlg::OnInitDialog()
{
    CResizableStandAloneDialog::OnInitDialog();
    CAppUtils::MarkWindowAsUnpinnable(m_hWnd);

    ExtendFrameIntoClientArea(IDC_EXTGROUP);
    m_aeroControls.SubclassControl(this, IDC_DOSWITCH);
    m_aeroControls.SubclassControl(this, IDC_MAKEPARENTS);
    m_aeroControls.SubclassOkCancelHelp(this);
    m_bCancelled = false;

    DWORD exStyle = LVS_EX_FULLROWSELECT | LVS_EX_DOUBLEBUFFER | LVS_EX_CHECKBOXES;
    m_ExtList.SetExtendedStyle(exStyle);
    SetWindowTheme(m_ExtList.GetSafeHwnd(), L"Explorer", NULL);
    m_ExtList.ShowText(CString(MAKEINTRESOURCE(IDS_COPY_WAITFOREXTERNALS)));

    AdjustControlSize(IDC_COPYHEAD);
    AdjustControlSize(IDC_COPYREV);
    AdjustControlSize(IDC_COPYWC);
    AdjustControlSize(IDC_DOSWITCH);
    AdjustControlSize(IDC_MAKEPARENTS);

    CTSVNPath path(m_path);
    CString sWindowTitle;
    GetWindowText(sWindowTitle);
    CAppUtils::SetWindowTitle(m_hWnd, path.GetUIPathString(), sWindowTitle);

    m_History.SetMaxHistoryItems((LONG)CRegDWORD(L"Software\\TortoiseSVN\\MaxHistoryItems", 25));

    SetRevision(m_CopyRev);

    m_tooltips.AddTool(IDC_HISTORY, IDS_COMMITDLG_HISTORY_TT);

    if (SVN::PathIsURL(path))
    {
        DialogEnableWindow(IDC_COPYWC, FALSE);
        DialogEnableWindow(IDC_DOSWITCH, FALSE);
        SetDlgItemText(IDC_COPYSTARTLABEL, CString(MAKEINTRESOURCE(IDS_COPYDLG_FROMURL)));
    }

    SVN svn;
    CString sUUID;
    m_repoRoot = svn.GetRepositoryRootAndUUID(path, true, sUUID);
    m_repoRoot.TrimRight('/');
    m_wcURL = svn.GetURLFromPath(path);
    if (m_wcURL.IsEmpty() || (!path.IsUrl() && !path.Exists()))
    {
        CString Wrong_URL=path.GetSVNPathString();
        CString temp;
        temp.Format(IDS_ERR_NOURLOFFILE, (LPCTSTR)Wrong_URL);
        ::MessageBox(this->m_hWnd, temp, L"TortoiseSVN", MB_ICONERROR);
        this->EndDialog(IDCANCEL);      //exit
    }
    m_URLCombo.LoadHistory(L"Software\\TortoiseSVN\\History\\repoPaths\\"+sUUID, L"url");
    m_URLCombo.SetCurSel(0);
    CString relPath = m_wcURL.Mid(m_repoRoot.GetLength());
    if (!m_URL.IsEmpty())
    {
        // allow the use of urls relative to the repo root
        if (m_URL[0] != '^')
            relPath = m_URL.Mid(m_repoRoot.GetLength());
        else
            relPath = m_URL.Mid(1);
    }
    CTSVNPath r = CTSVNPath(relPath);
    relPath = r.GetUIPathString();
    relPath.Replace('\\', '/');
    m_URLCombo.AddString(relPath, 0);
    m_URLCombo.SelectString(-1, relPath);
    m_URL = m_wcURL;
    SetDlgItemText(IDC_DESTURL, CPathUtils::CombineUrls(m_repoRoot, relPath));
    SetDlgItemText(IDC_FROMURL, m_wcURL);

    CString reg;
    reg.Format(L"Software\\TortoiseSVN\\History\\commit%s", (LPCTSTR)sUUID);
    m_History.Load(reg, L"logmsgs");

    m_ProjectProperties.ReadProps(m_path);
    if (CRegDWORD(L"Software\\TortoiseSVN\\AlwaysWarnIfNoIssue", FALSE))
        m_ProjectProperties.bWarnIfNoIssue = TRUE;

    m_cLogMessage.Init(m_ProjectProperties);
    m_cLogMessage.SetFont((CString)CRegString(L"Software\\TortoiseSVN\\LogFontName", L"Courier New"), (DWORD)CRegDWORD(L"Software\\TortoiseSVN\\LogFontSize", 8));

    GetDlgItem(IDC_BUGTRAQBUTTON)->ShowWindow(SW_HIDE);
    GetDlgItem(IDC_BUGTRAQBUTTON)->EnableWindow(FALSE);
    CBugTraqAssociations bugtraq_associations;
    bugtraq_associations.Load(m_ProjectProperties.GetProviderUUID(), m_ProjectProperties.sProviderParams);

    if (bugtraq_associations.FindProvider(CTSVNPathList(m_path), &m_bugtraq_association))
    {
        CComPtr<IBugTraqProvider> pProvider;
        HRESULT hr = pProvider.CoCreateInstance(m_bugtraq_association.GetProviderClass());
        if (SUCCEEDED(hr))
        {
            m_BugTraqProvider = pProvider;
            ATL::CComBSTR temp;
            ATL::CComBSTR parameters;
            parameters.Attach(m_bugtraq_association.GetParameters().AllocSysString());
            hr = pProvider->GetLinkText(GetSafeHwnd(), parameters, &temp);
            if (SUCCEEDED(hr))
            {
                SetDlgItemText(IDC_BUGTRAQBUTTON, temp == 0 ? L"" : temp);
                GetDlgItem(IDC_BUGTRAQBUTTON)->EnableWindow(TRUE);
                GetDlgItem(IDC_BUGTRAQBUTTON)->ShowWindow(SW_SHOW);
            }
        }

        GetDlgItem(IDC_LOGMESSAGE)->SetFocus();
    }
    if (m_ProjectProperties.sMessage.IsEmpty())
    {
        GetDlgItem(IDC_BUGID)->ShowWindow(SW_HIDE);
        GetDlgItem(IDC_BUGIDLABEL)->ShowWindow(SW_HIDE);
        GetDlgItem(IDC_LOGMESSAGE)->SetFocus();
    }
    else
    {
        GetDlgItem(IDC_BUGID)->ShowWindow(SW_SHOW);
        GetDlgItem(IDC_BUGIDLABEL)->ShowWindow(SW_SHOW);
        if (!m_ProjectProperties.sLabel.IsEmpty())
            SetDlgItemText(IDC_BUGIDLABEL, m_ProjectProperties.sLabel);
        GetDlgItem(IDC_BUGID)->SetFocus();
    }

    if (!m_sLogMessage.IsEmpty())
        m_cLogMessage.SetText(m_sLogMessage);
    else
        m_cLogMessage.SetText(m_ProjectProperties.GetLogMsgTemplate(PROJECTPROPNAME_LOGTEMPLATEBRANCH));

    OnEnChangeLogmessage();

    m_linkControl.ConvertStaticToLink(m_hWnd, IDC_CHECKALL);
    m_linkControl.ConvertStaticToLink(m_hWnd, IDC_CHECKNONE);

    // line up all controls and adjust their sizes.
#define LINKSPACING 9
    RECT rc = AdjustControlSize(IDC_SELECTLABEL);
    rc.right -= 15; // AdjustControlSize() adds 20 pixels for the checkbox/radio button bitmap, but this is a label...
    rc = AdjustStaticSize(IDC_CHECKALL, rc, LINKSPACING);
    rc = AdjustStaticSize(IDC_CHECKNONE, rc, LINKSPACING);

    CAppUtils::SetAccProperty(m_cLogMessage.GetSafeHwnd(), PROPID_ACC_ROLE, ROLE_SYSTEM_TEXT);
    CAppUtils::SetAccProperty(m_cLogMessage.GetSafeHwnd(), PROPID_ACC_HELP, CString(MAKEINTRESOURCE(IDS_INPUT_ENTERLOG)));
    CAppUtils::SetAccProperty(m_cLogMessage.GetSafeHwnd(), PROPID_ACC_KEYBOARDSHORTCUT, L"Alt+"+CString(CAppUtils::FindAcceleratorKey(this, IDC_INVISIBLE)));

    CAppUtils::SetAccProperty(GetDlgItem(IDC_CHECKALL)->GetSafeHwnd(), PROPID_ACC_ROLE, ROLE_SYSTEM_LINK);
    CAppUtils::SetAccProperty(GetDlgItem(IDC_CHECKNONE)->GetSafeHwnd(), PROPID_ACC_ROLE, ROLE_SYSTEM_LINK);

    CAppUtils::SetAccProperty(m_URLCombo.GetSafeHwnd(), PROPID_ACC_KEYBOARDSHORTCUT, L"Alt+"+CString(CAppUtils::FindAcceleratorKey(this, IDC_TOURLLABEL)));
    CAppUtils::SetAccProperty(GetDlgItem(IDC_FROMURL)->GetSafeHwnd(), PROPID_ACC_KEYBOARDSHORTCUT, L"Alt+"+CString(CAppUtils::FindAcceleratorKey(this, IDC_COPYSTARTLABEL)));
    CAppUtils::SetAccProperty(GetDlgItem(IDC_DESTURL)->GetSafeHwnd(), PROPID_ACC_KEYBOARDSHORTCUT, L"Alt+"+CString(CAppUtils::FindAcceleratorKey(this, IDC_DESTLABEL)));

    AddAnchor(IDC_REPOGROUP, TOP_LEFT, TOP_RIGHT);
    AddAnchor(IDC_COPYSTARTLABEL, TOP_LEFT, TOP_RIGHT);
    AddAnchor(IDC_FROMURL, TOP_LEFT, TOP_RIGHT);
    AddAnchor(IDC_TOURLLABEL, TOP_LEFT);
    AddAnchor(IDC_URLCOMBO, TOP_LEFT, TOP_RIGHT);
    AddAnchor(IDC_BROWSE, TOP_RIGHT);
    AddAnchor(IDC_DESTLABEL, TOP_LEFT, TOP_RIGHT);
    AddAnchor(IDC_DESTURL, TOP_LEFT, TOP_RIGHT);
    AddAnchor(IDC_MSGGROUP, TOP_LEFT, MIDDLE_RIGHT);
    AddAnchor(IDC_HISTORY, TOP_LEFT);
    AddAnchor(IDC_BUGTRAQBUTTON, TOP_LEFT);
    AddAnchor(IDC_BUGIDLABEL, TOP_RIGHT);
    AddAnchor(IDC_BUGID, TOP_RIGHT);
    AddAnchor(IDC_INVISIBLE, TOP_RIGHT);
    AddAnchor(IDC_LOGMESSAGE, TOP_LEFT, MIDDLE_RIGHT);
    AddAnchor(IDC_FROMGROUP, MIDDLE_LEFT, MIDDLE_RIGHT);
    AddAnchor(IDC_COPYHEAD, MIDDLE_LEFT);
    AddAnchor(IDC_COPYREV, MIDDLE_LEFT);
    AddAnchor(IDC_COPYREVTEXT, MIDDLE_RIGHT);
    AddAnchor(IDC_BROWSEFROM, MIDDLE_RIGHT);
    AddAnchor(IDC_COPYWC, MIDDLE_LEFT);
    AddAnchor(IDC_EXTGROUP, MIDDLE_LEFT, BOTTOM_RIGHT);
    AddAnchor(IDC_SELECTLABEL, MIDDLE_LEFT);
    AddAnchor(IDC_CHECKALL, MIDDLE_LEFT);
    AddAnchor(IDC_CHECKNONE, MIDDLE_LEFT);
    AddAnchor(IDC_EXTERNALSLIST, MIDDLE_LEFT, BOTTOM_RIGHT);
    AddAnchor(IDC_DOSWITCH, BOTTOM_LEFT);
    AddAnchor(IDC_MAKEPARENTS, BOTTOM_LEFT);
    AddAnchor(IDOK, BOTTOM_RIGHT);
    AddAnchor(IDCANCEL, BOTTOM_RIGHT);
    AddAnchor(IDHELP, BOTTOM_RIGHT);

    if ((m_pParentWnd==NULL)&&(GetExplorerHWND()))
        CenterWindow(CWnd::FromHandle(GetExplorerHWND()));
    EnableSaveRestore(L"CopyDlg");

    m_bSettingChanged = false;
    if (!m_path.IsUrl())
    {
        // start a thread to obtain the highest revision number of the working copy
        // without blocking the dialog
        if ((m_pThread = AfxBeginThread(FindRevThreadEntry, this))==NULL)
        {
            OnCantStartThread();
        }
    }

    return TRUE;
}
Example #30
0
void KeywordManager::RemoveProjects(vector<string> & removed_projects)
{
	vector<ProjectKeywords> current_projects;

	char *folder="Keyword Files\\";
	string path;

	//remove projects from memory
	for(UINT i=0; i<removed_projects.size(); i++)
	{
		vector<ProjectKeywords>::iterator project_iter = v_all_project_keywords.begin();
		for(UINT j=0; j<v_all_project_keywords.size(); j++)
		{
			if(strcmp(v_all_project_keywords[j].m_project_name.c_str(), removed_projects[i].c_str())==NULL)
			{	
				v_all_project_keywords.erase(project_iter);
				break;
			}

			project_iter++;
		}
		project_iter = v_project_keywords.begin();
		for(UINT j=0; j<v_project_keywords.size(); j++)
		{
			if(strcmp(v_project_keywords[j].m_project_name.c_str(), removed_projects[i].c_str())==NULL)
			{	
				v_project_keywords.erase(project_iter);
				break;
			}

			project_iter++;
		}
	}

	//remove project files
	WIN32_FIND_DATA file_data;
	path=folder;
	path+="*.kwd";
	HANDLE search_handle = ::FindFirstFile(path.c_str(), &file_data);
	BOOL found = FALSE;

	int count = 0;

	if (search_handle!=INVALID_HANDLE_VALUE)
	{
		found = TRUE;
	}


	while(found == TRUE)
	{
		for(UINT i=0; i<removed_projects.size(); i++)
		{	
			char file_project_name[256];
			strcpy(file_project_name, file_data.cFileName);
			CString project = removed_projects[i].c_str();
			project.Replace('\\','_');			// replace the backslash with _
			project.Replace('\'', '_');		// replace the single quote "'" with _
			project.Replace(' ', '_');
			project.Replace('-', '_');
			project.Replace('&', '_');
			project.Replace('!', '_');
			project.Replace('$', '_');
			project.Replace('@', '_');
			project.Replace('%', '_');
			project.Replace('(', '_');
			project.Replace(')', '_');
			project.Replace('+', '_');
			project.Replace('~', '_');
			project.Replace('*', '_');
			project.Replace('.', '_');
			project.Replace(',', '_');
			project.Replace('?', '_');
			project.Replace(':', '_');
			project.Replace(';', '_');
			project.Replace('"', '_');
			project.Replace('/', '_');
			project += ".kwd";

			if(strcmp(project, file_project_name)==NULL)
			{
				path=folder;
				path+=file_data.cFileName;
				CFile::Remove(path.c_str());
				break;
			}
		}

		found = ::FindNextFile(search_handle, &file_data);


	}
	
	::FindClose(search_handle);

}