Example #1
0
BOOL CDlgStrategyHQ::OnInitDialog() 
{
	CDialog::OnInitDialog();
	m_bSetVar = FALSE;
// 	m_wndPeriod.ResetContent();
// 	AddPeriodNameToWnd(&m_wndPeriod);

	m_EditEidolon.CreateEx(WS_EX_CLIENTEDGE,NULL,NULL,WS_CHILD|WS_VISIBLE|WS_TABSTOP|WS_BORDER,
		CRect(0,0,0,0),this,1001);
	m_EditEidolon.SetFont( GetFont() );

	CRect rect;
	CWnd* pWnd = GetDlgItem(IDC_PARAM);
	pWnd->GetWindowRect(&rect);
	ScreenToClient(&rect);
	m_EditEidolon.MoveWindow(rect);

	CTreeCtrlFormula* pCurTree = m_wndTab.GetTree();
	if( pCurTree )
	{
		CDlgFormulaMan* pDlg = (CDlgFormulaMan*)AfxGetMainWnd();

		pCurTree->ModifyStyleEx(0,WS_EX_CLIENTEDGE);
		pCurTree->SetImageList(&CDlgFormulaMan::m_expressImages, TVSIL_NORMAL);
		pCurTree->m_pFormulaMan = pDlg;

		if( m_pData != NULL )
		{
			WORD nType = ((m_pData->m_wType & 0xFF) & Strategy);
			int nCopy = CTreeCtrlFormula::CopyNone;
			CTreeCtrlFormula* pTree;
			for( int i = 0; i < 5; i++ ) //20090302 YJT 修改
			{
				switch(i)
				{
				case 0:
					nType = ((m_pData->m_wType & 0xF) & Tech);
					break;
				case 1:
					nType = ((m_pData->m_wType & 0xF) & Condition);
					break;
				case 2:
					nType = ((m_pData->m_wType & 0xF) & Exchange);
					break;
				case 3:
					nType = ((m_pData->m_wType & 0xF) & MoreKLine);
					break;
				case 4:
					nType = ((m_pData->m_wType & 0xFF) & Strategy);
					break;
				}

				pTree = pDlg->GetCurTree( nType );
				pCurTree->CopyTree(pTree,nCopy,m_pData->m_dStyle);
			}

			if (m_pStrategy->m_pData && m_pStrategy->m_pData->m_pCurVal)
			{ 
				CString cs;
				char c[7] = {0};
				strncpy(c,m_pStrategy->m_cCode,6);
				m_wndCode.SetWindowText(c);//股票代码
				//--------------------------------------------
				switch(m_pStrategy->m_nPeriodType)
				{
				case AnalisysFor1:
					cs = "1分钟";
					break;
				case AnalisysFor5:
					cs = "5分钟";
					break;
				case AnalisysFor15:
					cs = "15分钟";
					break;
				case AnalisysFor30:
					cs = "30分钟";
					break;
				case AnalisysFor60:
					cs = "60分钟";
					break;
				case AnalisysForDay:
					cs = "日线";
					break;
				case AnalisysForWeek:
					cs = "周线";
					break;
				case AnalisysForMonth:
					cs = "月线";
					break;
				default:
					cs = "多日线";
					break;
				}
				if (cs == "多日线" || cs.IsEmpty())
				{
					m_wndDay.EnableWindow(TRUE);
				}
				m_wndCycle.SelectString(-1,cs);
				//--------------------------------------------------
				cs.Format("%d",m_pStrategy->m_nMaxBuyTimes);
				m_wndBuyTimes.SetWindowText(cs);
				cs.Format("%d",m_pStrategy->m_nMaxSellTimes);
				m_wndSellTimes.SetWindowText(cs);
				cs.Format("%d",m_pStrategy->m_nTrigTimes);
				m_wndTriggerTime.SetWindowText(cs);
				cs.Format("%d",m_pStrategy->m_nMaxTrigTimes);
				m_wndTrigerNum.SetWindowText(cs);
				cs.Format("%d",m_pStrategy->m_nPeriodNumber);
				m_wndDay.SetWindowText(cs);
				cs.Format("%d",m_pStrategy->m_nGap);
				m_wndGap.SetWindowText(cs);
				if (m_pStrategy->m_bFuQuan == 0)
				{
					m_wndCheck.SetCheck(TRUE);	
				}
				if (m_pStrategy->m_bXD == 1)
				{
					m_wndXD.SetCheck(TRUE);
				}
				CArray<CTreeGroup*,CTreeGroup*>* pTreeGp = pCurTree->GetTreeGroup();
				int sel = 0;
				for (; sel<pTreeGp->GetCount(); sel++)
				{
					CTreeGroup *pGp = pTreeGp->GetAt(sel);
					CString csName = pGp->GetName();
					CString cExpName = m_pStrategy->m_sExpName;
					if (pGp && csName == cExpName)
					{
						break;
					}
				}

				if (sel < pTreeGp->GetCount())
				{
					CTreeGroup *ptg = pTreeGp->GetAt(sel);					
					
					m_bSetVar = TRUE;
					pCurTree->Show(ptg->GetData(),0);
			
				}
				else
				{
					pCurTree->Show(NULL,0);
				}
			}
			else
				pCurTree->Show(NULL,0);
		}

	}

	return TRUE;  // return TRUE unless you set the focus to a control
	// EXCEPTION: OCX Property Pages should return FALSE
}
Example #2
0
BOOL CDrawQuoteTabCtrl::ChangeTabGroup( CString strGroup /*= _T("")*/, BOOL bForce /*= FALSE*/ )
{
	if (strGroup.IsEmpty())
	{
		strGroup = GetDefaultTabGroupName();
	}
	if (m_strCurGroupName == strGroup && !bForce)
	{
		return FALSE;
	}	
	m_strCurGroupName = strGroup;
	m_nCurItem = -1;

	PageInfo pageInfo;
	CTabItemArray ayTabItem;
	LONG nCount = m_iTab->GetTabList(strGroup, ayTabItem);
	if (nCount <= 0)
	{
		return FALSE;
	}

	RemoveTabItem(-1);
	int nItemID = m_iTab->GetDefaultTabItemID();
	int nDefault(0);

	CArray<StockType> ayBlockMarket;
	TabItem* pItem = NULL;
	for (int i = 0, j = 0; i < nCount; i++)
	{
		pItem = ayTabItem.GetAt(i);

		ayBlockMarket.RemoveAll();
		m_pDataSource->HSDataSourceEx_GetSystemMarketInfo((unsigned short*)pItem->m_sMarket, MARKETTYPE_COUNT, ayBlockMarket);
		if (ayBlockMarket.GetCount() != 0)
		{
			// 如果服务器当面配置了名称 以服务器那边的名称为主
			strncpy(pItem->m_szName, ayBlockMarket.GetAt(0).m_stTypeName.m_szName, min(strlen(pItem->m_szName), strlen(ayBlockMarket.GetAt(0).m_stTypeName.m_szName)));
			j++;
		}

		if (pItem->m_ID == nItemID)
			nDefault = j - 1;
		
		pageInfo.m_lPageType = pItem->m_lPageType;
		pageInfo.m_lInPageTag = pItem->m_lPageTag;
		for (int i = 0; i < MARKETTYPE_COUNT; i++)
		{
			pageInfo.m_sMarket[i] = pItem->m_sMarket[i];
		}
		memcpy(pageInfo.m_szBlock,pItem->m_szBlock,BLOCK_NAME_LENGTH);
		AddTabItem(pItem->m_szName, pItem->m_ID, pItem->m_lMenuMask, &pageInfo, pItem->m_szColGroupName);
	}
	if (strGroup == GetDefaultTabGroupName())
	{
		ChangeCurItem(nDefault);
	}
	else
		ChangeCurItem(0);
//	m_nLeftOffset = 0;
//	Invalidate(FALSE);
	return TRUE;
}
Example #3
0
void CMainFrame::OnDutyOff()
{
#ifndef _DEBUG
	if (!CRightsManagement::GetInstance()->Take_IBAP_ONOFFDUTY(FALSE))
	{
		return;
	}
#endif
	
	//{ 2011/08/11-8201-gxx: 
	
	BOOL bNormal = TRUE;
	if (CIBAGlobal::NetworkStatus == CIBAGlobal::emNetworkRestore)
	{
		bNormal = FALSE;
	}
	else
	{
		CArray<CLocalConsumeInfo,CLocalConsumeInfo&> InfoArray; 
		CIBADAL::GetInstance()->GetLocalConsumes(InfoArray);
		if (InfoArray.GetCount() > 0)
		{
			bNormal = FALSE;
		}
	}

	if (theApp.GetCurCashier()->IsOnDuty() == FALSE)
	{
		bNormal = TRUE; // 能弹出上班界面
	}
	
	//}

	if (bNormal)
	{
		CDlgIBADuty dlg;

		if (theApp.GetCurCashier()->IsOnDuty())//是否在上班
		{
			if (dlg.DoModal() == IDOK)
			{
				//{ 2011/04/19-gxx: 判断在交班的时候,IBA是否有更新
				theApp.UpdateIBA();
				//}

				CJXCMainDlg::DestroyJxcMainDlg();//销毁非模态的进销存对话框

				UpdateStatusText();//更新状态栏

				CIBALoginDlg dlg2;//登入对话框
				dlg2.SetLoginType(1);//调整位置,不对原顶层窗体做要求

				if (dlg2.DoModal() == IDOK)
				{
					UpdateStatusText();//更新状态栏
				}
				else
				{
					CBCGPFrameWnd::OnClose();//退出
				}
			}
		}
		else
		{
			dlg.DoModal();
			UpdateStatusText();
		}
	}
	else
	{
		CDlgDutyLocal dlg;
		dlg.DoModal();
	}
}
Example #4
0
void CToolBarCtrlZ::DrawItem(CDC *pDC, int iIndex, const CRect &rtItem, BOOL bHover)
{
	UINT			uItemId;
	UINT			uItemState;
	TBBUTTON		tbb;


	TCHAR			szText[1024];
	TBBUTTONINFO	tbi;
	CArray<CxImage*, CxImage*>	*parrImgs = NULL;
	CxImage			*pIconImg = NULL;		
	int				iIconTop;
	CRect			rtDraw;
	CRect			rtText;
	COLORREF		clrText;
	
	CClientRect		rtClient(this);
	rtDraw = rtItem;
	rtDraw.top = rtClient.top;
	rtDraw.bottom = rtClient.bottom;

	if (!GetButton(iIndex, &tbb))
		return;

	uItemId = tbb.idCommand;
	uItemState = GetState(uItemId);

	parrImgs = &m_arrImgs;
	if ( !IsButtonEnabled(uItemId) )
	{
		clrText = RGB(204, 128, 128);
		if (0 != m_arrDisableImgs.GetCount())
			parrImgs = &m_arrDisableImgs;
	}
	else
	{
		clrText = RGB(255, 254, 253);

		if (TBSTATE_PRESSED & uItemState/*IsButtonPressed(uItemId)*/)
			rtDraw.OffsetRect(1, 1);
		else if (bHover/*iIndex == GetHotItem()*/)
			rtDraw.OffsetRect(-1, -2);
	}


	ZeroMemory(&tbi, sizeof(TBBUTTONINFO));
	tbi.cbSize = sizeof(TBBUTTONINFO);
	tbi.dwMask = TBIF_TEXT | TBIF_IMAGE;
	tbi.pszText = szText;
	tbi.cchText = 1024;
	//if (GetButtonInfo(p->nmcd.dwItemSpec, &tbi))
	GetButtonInfo(uItemId, &tbi);
	{

		rtText = rtDraw;

		if (tbi.iImage < parrImgs->GetCount())
		{
			pIconImg = parrImgs->GetAt(tbi.iImage);
			if (NULL != pIconImg)
			{
				iIconTop = rtDraw.Height() - pIconImg->GetHeight();
				iIconTop /= 2;
				iIconTop += rtDraw.top;
				pIconImg->Draw(pDC->GetSafeHdc(), rtDraw.left, iIconTop);
				rtText.left += pIconImg->GetWidth() + 4;
			}
		}


		{
			CWndFontDC	fontDC(pDC->GetSafeHdc(), GetSafeHwnd());
			CTextDC		textDC(pDC->GetSafeHdc(), clrText);
			
			pDC->DrawText(tbi.pszText, -1, &rtText, DT_LEFT | DT_VCENTER | DT_SINGLELINE);
		}
	}

}
Example #5
0
CStringW CMpeg2DataParser::ConvertString(BYTE* pBuffer, size_t uLength)
{
    static const UINT16 codepages[0x20] = {
        20269,  // 00 - Default ISO/IEC 6937
        28595,  // 01 - ISO 8859-5 Cyrillic
        28596,  // 02 - ISO 8859-6 Arabic
        28597,  // 03 - ISO 8859-7 Greek
        28598,  // 04 - ISO 8859-8 Hebrew
        28599,  // 05 - ISO 8859-9 Latin 5
        28591,  // 06 - ??? - ISO/IEC 8859-10 - Latin alphabet No. 6
        28591,  // 07 - ??? - ISO/IEC 8859-11 - Latin/Thai (draft only)
        28591,  // 08 - reserved
        28603,  // 09 - ISO 8859-13 - Estonian
        28591,  // 0a - ??? - ISO/IEC 8859-14 - Latin alphabet No. 8 (Celtic)
        28605,  // 0b - ISO 8859-15 Latin 9
        28591,  // 0c - reserved
        28591,  // 0d - reserved
        28591,  // 0e - reserved
        28591,  // 0f - reserved
        0,      // 10 - See codepages10 array
        28591,  // 11 - ??? - ISO/IEC 10646 - Basic Multilingual Plane (BMP)
        28591,  // 12 - ??? - KSX1001-2004 - Korean Character Set
        20936,  // 13 - Chinese Simplified (GB2312-80)
        950,    // 14 - Chinese Traditional (Big5)
        28591,  // 15 - ??? - UTF-8 encoding of ISO/IEC 10646 - Basic Multilingual Plane (BMP)
        28591,  // 16 - reserved
        28591,  // 17 - reserved
        28591,  // 18 - reserved
        28591,  // 19 - reserved
        28591,  // 1a - reserved
        28591,  // 1b - reserved
        28591,  // 1c - reserved
        28591,  // 1d - reserved
        28591,  // 1e - reserved
        28591   // 1f - TODO!
    };

    static const UINT16 codepages10[0x10] = {
        28591,  // 00 - reserved
        28591,  // 01 - ISO 8859-1 Western European
        28592,  // 02 - ISO 8859-2 Central European
        28593,  // 03 - ISO 8859-3 Latin 3
        28594,  // 04 - ISO 8859-4 Baltic
        28595,  // 05 - ISO 8859-5 Cyrillic
        28596,  // 06 - ISO 8859-6 Arabic
        28597,  // 07 - ISO 8859-7 Greek
        28598,  // 08 - ISO 8859-8 Hebrew
        28599,  // 09 - ISO 8859-9 Turkish
        28591,  // 0a - ??? - ISO/IEC 8859-10
        28591,  // 0b - ??? - ISO/IEC 8859-11
        28591,  // 0c - ??? - ISO/IEC 8859-12
        28603,  // 0d - ISO 8859-13 Estonian
        28591,  // 0e - ??? - ISO/IEC 8859-14
        28605,  // 0f - ISO 8859-15 Latin 9

        // 0x10 to 0xFF - reserved for future use
    };

    CStringW strResult;
    if (uLength > 0) {
        UINT cp = CP_ACP;
        int nDestSize;

        if (pBuffer[0] == 0x10) {
            pBuffer++;
            uLength--;
            if (pBuffer[0] == 0x00) {
                cp = codepages10[pBuffer[1]];
            } else { // if (pBuffer[0] > 0x00)
                // reserved for future use, use default codepage
                cp = codepages[0];
            }
            pBuffer += 2;
            uLength -= 2;
        } else if (pBuffer[0] < 0x20) {
            cp = codepages[pBuffer[0]];
            pBuffer++;
            uLength--;
        } else { // No code page indication, use the default
            cp = codepages[0];
        }

        // Work around a bug in MS MultiByteToWideChar with ISO/IEC 6937 and take care of the Euro symbol special case (step 1/2)...
        CArray<size_t> euroSymbolPos;
        if (cp == 20269) {
            BYTE tmp;
            for (size_t i = 0; i < uLength - 1; i++) {
                if (pBuffer[i] >= 0xC1 && pBuffer[i] <= 0xCF && pBuffer[i] != 0xC9 && pBuffer[i] != 0xCC) {
                    // Swap the current char with the next one
                    tmp = pBuffer[i];
                    pBuffer[i] = pBuffer[i + 1];
                    pBuffer[++i] = tmp;
                } else if (pBuffer[i] == 0xA4) { // € was added as 0xA4 in the DVB spec
                    euroSymbolPos.Add(i);
                }
            }
            // Handle last symbol if it's a €
            if (pBuffer[uLength - 1] == 0xA4) {
                euroSymbolPos.Add(uLength - 1);
            }
        }

        nDestSize = MultiByteToWideChar(cp, MB_PRECOMPOSED, (LPCSTR)pBuffer, (int)uLength, nullptr, 0);
        if (nDestSize > 0) {
            LPWSTR strResultBuff = strResult.GetBuffer(nDestSize);
            MultiByteToWideChar(cp, MB_PRECOMPOSED, (LPCSTR)pBuffer, (int)uLength, strResultBuff, nDestSize);

            // Work around a bug in MS MultiByteToWideChar with ISO/IEC 6937 and take care of the Euro symbol special case (step 2/2)...
            if (cp == 20269) {
                for (size_t i = 0, len = (size_t)nDestSize; i < len; i++) {
                    switch (strResultBuff[i]) {
                        case 0x60: // grave accent
                            strResultBuff[i] = 0x0300;
                            break;
                        case 0xb4: // acute accent
                            strResultBuff[i] = 0x0301;
                            break;
                        case 0x5e: // circumflex accent
                            strResultBuff[i] = 0x0302;
                            break;
                        case 0x7e: // tilde
                            strResultBuff[i] = 0x0303;
                            break;
                        case 0xaf: // macron
                            strResultBuff[i] = 0x0304;
                            break;
                        case 0xf8f8: // dot
                            strResultBuff[i] = 0x0307;
                            break;
                    }
                }

                for (INT_PTR i = 0, len = euroSymbolPos.GetCount(); i < len; i++) {
                    strResultBuff[euroSymbolPos[i]] = _T('€');
                }
            }

            // Some strings seems to be null-terminated, we need to take that into account.
            while (nDestSize > 0 && strResultBuff[nDestSize - 1] == L'\0') {
                nDestSize--;
            }

            strResult.ReleaseBuffer(nDestSize);
        }
    }

    return strResult;
}
void CRevisionGraphWnd::DrawConnections (GraphicsDevice& graphics, const CRect& /*logRect*/, const CSize& offset)
{

	CArray<PointF> points;
	CArray<CPoint> pts;

	if(graphics.graphics)
		graphics.graphics->SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);

	float penwidth = 2*m_fZoomFactor<1? 1:2*m_fZoomFactor;
	Gdiplus::Pen pen(Color(0,0,0),penwidth);

	// iterate over all visible lines
	edge e;
	forall_edges(e, m_Graph)
	{
		// get connection and point position
		const DPolyline &dpl = this->m_GraphAttr.bends(e);

		points.RemoveAll();
		pts.RemoveAll();

		PointF pt;
		pt.X = (REAL)m_GraphAttr.x(e->source());
		pt.Y = (REAL)m_GraphAttr.y(e->source());

		points.Add(pt);

		ListConstIterator<DPoint> it;
		for(it = dpl.begin(); it.valid(); ++it)
		{
			pt.X =  (REAL)(*it).m_x;
			pt.Y =  (REAL)(*it).m_y;
			points.Add(pt);
		}

		pt.X = (REAL)m_GraphAttr.x(e->target());
		pt.Y = (REAL)m_GraphAttr.y(e->target());

		points.Add(pt);

		points[0] = this->cutPoint(e->source(), 1, points[0], points[1]);
		points[points.GetCount()-1] =  this->cutPoint(e->target(), 1, points[points.GetCount()-1], points[points.GetCount()-2]);
		// draw the connection

		for (int i = 0; i < points.GetCount(); ++i)
		{
			//CPoint pt;
			points[i].X = points[i].X * this->m_fZoomFactor - offset.cx;
			points[i].Y = points[i].Y * this->m_fZoomFactor - offset.cy;
			//pts.Add(pt);
		}

		if (graphics.graphics)
		{
			graphics.graphics->DrawLines(&pen, points.GetData(), (INT)points.GetCount());

		}
		else if (graphics.pSVG)
		{
			Color color;
			color.SetFromCOLORREF(GetSysColor(COLOR_WINDOWTEXT));
			graphics.pSVG->Polyline(points.GetData(), (int)points.GetCount(), Color(0,0,0), (int)penwidth);
		}
		else if (graphics.pGraphviz)
		{
			CString hash1 = _T("g") + m_logEntries[e->target()->index()].ToString().Left(g_Git.GetShortHASHLength());
			CString hash2 = _T("g") + m_logEntries[e->source()->index()].ToString().Left(g_Git.GetShortHASHLength());
			graphics.pGraphviz->DrawEdge(hash1, hash2);
		}

		//draw arrow
		double dx = points[1].X - points[0].X;
		double dy = points[1].Y - points[0].Y;

		double len = sqrt(dx*dx + dy*dy);
		dx = m_ArrowSize * m_fZoomFactor *dx /len;
		dy = m_ArrowSize * m_fZoomFactor *dy /len;

		double p1_x, p1_y, p2_x, p2_y;
		p1_x = dx * m_ArrowCos - dy * m_ArrowSin;
		p1_y = dx * m_ArrowSin + dy * m_ArrowCos;

		p2_x = dx * m_ArrowCos + dy * m_ArrowSin;
		p2_y = -dx * m_ArrowSin + dy * m_ArrowCos;

		//graphics.graphics->DrawLine(&pen, points[0].X,points[0].Y, points[0].X +p1_x,points[0].Y+p1_y);
		//graphics.graphics->DrawLine(&pen, points[0].X,points[0].Y, points[0].X +p2_x,points[0].Y+p2_y);
		GraphicsPath path;

		PointF arrows[5];
		arrows[0].X =  points[0].X;
		arrows[0].Y =  points[0].Y;

		arrows[1].X =  points[0].X + (REAL)p1_x;
		arrows[1].Y =  points[0].Y + (REAL)p1_y;

		arrows[2].X =  points[0].X + (REAL)dx*3/5;
		arrows[2].Y =  points[0].Y + (REAL)dy*3/5;

		arrows[3].X =  points[0].X + (REAL)p2_x;
		arrows[3].Y =  points[0].Y + (REAL)p2_y;

		arrows[4].X =  points[0].X;
		arrows[4].Y =  points[0].Y;

		path.AddLines(arrows, 5);
		path.SetFillMode(FillModeAlternate);
		if(graphics.graphics)
		{
			graphics.graphics->DrawPath(&pen, &path);
		}else if(graphics.pSVG)
		{
			graphics.pSVG->DrawPath(arrows, 5, Color(0,0,0), (int)penwidth, Color(0,0,0));
		}
	}
}
Example #7
0
bool CGPIBDevice::ScanDevice(CArray<IO_ADDRESS> &addresses)
{
	IO_ADDRESS addrnode;
	addresses.RemoveAll();
	int res;

	if (m_hGPIBDLL == NULL && !LoadGPIBDriver())
	{
		return false;
	}

	short primary_addrs[MAX_GPIB_PRIM_ADDR];
	short addr[MAX_ADDRESSES];

	for (int nAddr = 0; nAddr < MAX_ADDRESSES; nAddr++)
	{
		addr[nAddr] = (short)0xFFFF;
	}

	for (int nAddr = 0; nAddr < (MAX_GPIB_PRIM_ADDR - 2); nAddr++)
	{
		primary_addrs[nAddr] = (short)(nAddr + 1);
	}

	primary_addrs[MAX_GPIB_PRIM_ADDR - 2] = (short)0xFFFF;

	Log(_T("GPIB device scanning start!"));

	for (int nBus = 0; nBus < MAX_GPIB_CARD; nBus++)
	{
		ibonl(nBus, 1); if (ibsta & ERR) continue;
		ibconfig(nBus, IbcSC, 1); if (ibsta & ERR) continue;
		ibsic(nBus); if (ibsta & ERR) continue;
		ibconfig(nBus, IbcSRE, 1); if (ibsta & ERR) continue;
		ibconfig(nBus, IbcTIMING, 1); if (ibsta & ERR) continue;
		ibask(nBus, IbaPAD, &res); if (ibsta & ERR) continue;
		ibask(nBus, IbaSAD, &res); if (ibsta & ERR) continue;

		FindLstn(nBus, primary_addrs, addr, MAX_ADDRESSES - 1);

		if (ibsta & ERR) continue;

		for (int i = 0; i < (MAX_ADDRESSES - 1); i++)
		{
			if (addr[i] == -1) break;

			memset(&addrnode, 0, sizeof(IO_ADDRESS));

			addrnode.nBus = nBus;
			addrnode.eType = DRV_GPIB;
			addrnode.nPrimAddr = (addr[i] & 0xFF);
			addrnode.nSecAddr = ((addr[i] & 0xFF00) >> 8);

			addrnode.bPrimary = (i == 0 || addresses[i - 1].nPrimAddr != addrnode.nPrimAddr);

			if (addrnode.bPrimary && !Open(nBus, addrnode.nPrimAddr, addrnode.nSecAddr)) continue;

			if (!addrnode.bPrimary)
				strcpy_s(addrnode.sDevIdentity, addresses[i - 1].sDevIdentity);
			else
			{
				int nReadLen = MAX_DEV_IDN_LEN;
				CString strIDN;

				if (!Query("*IDN?", nReadLen, addrnode.sDevIdentity, 1000))
				{
					Log(CCommon::FormatString(_T("Failed to query identity of  device at GPIB::%d::%d::%d"), nBus, addrnode.nPrimAddr, addrnode.nSecAddr));

					Close();
					continue;
				}

				Close();
			}

			addresses.Add(addrnode);
		}
	}

	if (addresses.GetCount() == 0)
	{
		Log(_T("Found no GPIB device!"));
		return false;
	}

	return true;
}
void CKadLookupGraph::OnPaint()
{
	m_aNodesDrawRects.RemoveAll();
	CPaintDC pdc(this);

	CRect rcClnt;
	GetClientRect(&rcClnt);
	if (rcClnt.IsRectEmpty())
		return;

	CMemDC dc(&pdc, rcClnt);
	CPen* pOldPen = dc.SelectObject(&m_penAxis);
	if (g_xpStyle.IsThemeActive() && g_xpStyle.IsAppThemed())
	{
		HTHEME hTheme = g_xpStyle.OpenThemeData(NULL, L"ListView");
		if (hTheme)
		{
			g_xpStyle.DrawThemeBackground(hTheme, dc.m_hDC, 3, 0, &rcClnt, NULL);
			g_xpStyle.CloseThemeData(hTheme);
		}
	}
	else
	{
		dc.Rectangle(&rcClnt);
	}
	rcClnt.DeflateRect(1, 1, 1, 1);
	dc.FillSolidRect(rcClnt, GetSysColor(COLOR_WINDOW));
	rcClnt.DeflateRect(1, 1, 1, 1);
	COLORREF crOldTextColor = dc.SetTextColor(GetSysColor(COLOR_WINDOWTEXT));

	CFont* pOldFont = dc.SelectObject(AfxGetMainWnd()->GetFont());
	if (!m_bInitializedFontMetrics)
	{
		TEXTMETRIC tm;
		dc.GetTextMetrics(&tm);
		// why is 'tm.tmMaxCharWidth' and 'tm.tmAveCharWidth' that wrong?
		CRect rcLabel;
		dc.DrawText(_T("888"), 3, &rcLabel, DT_CALCRECT);
		m_iMaxNumLabelWidth = rcLabel.Width();
		if (m_iMaxNumLabelWidth <= 0)
			m_iMaxNumLabelWidth = 3*8;
		m_iMaxLabelHeight = tm.tmHeight;
		if (m_iMaxLabelHeight <= 0)
			m_iMaxLabelHeight = 8;
		m_bInitializedFontMetrics = true;
	}

	int iLeftBorder = 3;
	int iRightBorder = 8;
	int iTopBorder = m_iMaxLabelHeight;
	int iBottomBorder = m_iMaxLabelHeight;

	int iBaseLineX = iLeftBorder;
	int iBaseLineY = rcClnt.bottom - iBottomBorder;
	UINT uHistWidth = rcClnt.Width() - iLeftBorder - iRightBorder;
	UINT uHistHeight = rcClnt.Height() - iTopBorder - iBottomBorder;
	if (uHistHeight == 0) {
		dc.SelectObject(pOldFont);
		dc.SetTextColor(crOldTextColor);
		return;
	}


	dc.MoveTo(iBaseLineX, rcClnt.top + iTopBorder);
	dc.LineTo(iBaseLineX, iBaseLineY);
	dc.LineTo(iBaseLineX + uHistWidth, iBaseLineY);

	dc.SelectObject(&m_penAux);

	CRect rcLabel(rcClnt);
	rcLabel.left = iBaseLineX;
	rcLabel.bottom = m_iMaxLabelHeight;
	dc.DrawText(m_strYaxis, m_strYaxis.GetLength(), &rcLabel, DT_LEFT | DT_TOP | DT_NOCLIP);

	rcLabel = rcClnt;
	rcLabel.top = rcClnt.bottom - m_iMaxLabelHeight + 1;
	dc.DrawText(m_strXaxis, m_strXaxis.GetLength(), &rcLabel, DT_RIGHT | DT_BOTTOM | DT_NOCLIP);

	if (m_pLookupHistory != NULL && m_pLookupHistory->GetHistoryEntries().GetCount() >= 1)
	{
		// How many nodes can we show without scrolling?
		sint32 uMaxNodes = uHistWidth / NODE_ENTRY_WIDTH;
		uint32 uNodeEntryWidth = 0;
		if (m_pLookupHistory->GetHistoryEntries().GetCount() > uMaxNodes /*|| !m_pLookupHistory->IsSearchStopped()*/)
			uNodeEntryWidth = NODE_ENTRY_WIDTH; // While the search is running, use a fixed width
		else
			uNodeEntryWidth = uHistWidth / m_pLookupHistory->GetHistoryEntries().GetCount(); // when the search is finished, use all available screen space

		sint32 iVisibleNodes = min(uMaxNodes, m_pLookupHistory->GetHistoryEntries().GetCount());

		// Set the scaling. 3 times the highest distance of the 1/3 closest nodes is the max distance
		CArray<CUInt128> aClosest;
		for (int i = 1; i <= iVisibleNodes; i++)
		{
			if (aClosest.GetCount() < ((iVisibleNodes / 3 == 0) ? 1 : (iVisibleNodes / 3)))
				aClosest.Add(m_pLookupHistory->GetHistoryEntries()[m_pLookupHistory->GetHistoryEntries().GetCount() - i]->m_uDistance);
			else
			{
				int iReplace = -1;
				for (int j = 0; j < aClosest.GetCount(); j++)
				{
					if ((iReplace == (-1) && aClosest[j] > m_pLookupHistory->GetHistoryEntries()[m_pLookupHistory->GetHistoryEntries().GetCount() - i]->m_uDistance)
						|| (iReplace >= 0 && aClosest[j] > aClosest[iReplace]))
					{
						iReplace = j;
					}
				}
				if (iReplace >= 0)
					aClosest[iReplace] = m_pLookupHistory->GetHistoryEntries()[m_pLookupHistory->GetHistoryEntries().GetCount() - i]->m_uDistance;
			}
		}
		CUInt128 uTmpScalingDistance((ULONG)0);
		for (int j = 0; j < aClosest.GetCount(); j++)
		{
			if (aClosest[j] > uTmpScalingDistance)
				uTmpScalingDistance = aClosest[j];
		}
		// Convert it to uint64 by cutting of the less significant bits for easier and fast calculating
		uint64 uScalingDistance = 0;
		uint8 byStartChunk;
		for (byStartChunk = 0;  byStartChunk < 3; byStartChunk++)
		{
			if (uTmpScalingDistance.Get32BitChunk(byStartChunk) > 0)
			{
				uScalingDistance = ((uint64)uTmpScalingDistance.Get32BitChunk(byStartChunk) << 32) + (uint64)uTmpScalingDistance.Get32BitChunk(byStartChunk + 1);
				break;
			}
		}
		if (uScalingDistance == 0)
		{
			byStartChunk = 2;
			uScalingDistance = uTmpScalingDistance.Get32BitChunk(3);
		}
		uScalingDistance /= (uHistHeight - NODE_ENTRY_HEIGHT);
		uScalingDistance *= 3;
		ASSERT(uScalingDistance > 0);
		if (uScalingDistance == 0)
			uScalingDistance = 1;


		//if (m_bDbgLog)
		//	AddDebugLogLine(false, _T("KadGraph: Considering %u of %u Nodes, 1/3 Max Distance found: %s"), iVisibleNodes, m_pLookupHistory->GetHistoryEntries().GetCount(), uTmpScalingDistance.ToHexString());  

		CUInt128 uMaxScalingDistance(uTmpScalingDistance);
		uMaxScalingDistance.Add(uTmpScalingDistance);
		uMaxScalingDistance.Add(uTmpScalingDistance);

		// wow, what a mess, now lets collect drawing points
		for (int i = 1; i <= iVisibleNodes; i++)
		{
			CUInt128 uTmpDist = m_pLookupHistory->GetHistoryEntries()[m_pLookupHistory->GetHistoryEntries().GetCount() - i]->m_uDistance;
			uint64 uDrawYPos;
			if (uTmpDist > uMaxScalingDistance)
				uDrawYPos = iTopBorder;
			else
			{
				uDrawYPos = (((uint64)uTmpDist.Get32BitChunk(byStartChunk) << 32) + (uint64)uTmpDist.Get32BitChunk(byStartChunk + 1));
				if (uDrawYPos > 0)
					uDrawYPos /= uScalingDistance;
				uDrawYPos = (iBaseLineY - NODE_ENTRY_HEIGHT) - uDrawYPos;
			}
			//if (m_bDbgLog)
			//	AddDebugLogLine(false, _T("KadGraph: Drawing Node %u of %u, Distance: %s, Y-Pos: %u"), (iVisibleNodes - i) + 1, iVisibleNodes, uTmpDist.ToHexString(), uDrawYPos); 

			ASSERT( uDrawYPos <= (uHistHeight) );
			uint32 nXOffset = 0;
			//if (uMaxNodes > iVisibleNodes && !m_pLookupHistory->IsSearchStopped()) // Fixed width for ongoing searches
			//	nXOffset = NODE_ENTRY_WIDTH * (uMaxNodes - iVisibleNodes);
			CPoint pointNode(uHistWidth - nXOffset - (i * uNodeEntryWidth), (uint32)uDrawYPos);
			m_aNodesDrawRects.Add(CRect(pointNode, CSize(NODE_ENTRY_WIDTH, NODE_ENTRY_HEIGHT)));
		}
		ASSERT( iVisibleNodes == m_aNodesDrawRects.GetCount() );

		// find HotItem (if any)
		m_iHotItemIdx = (-1);
		CPoint ptCursor;
		if (GetCursorPos(&ptCursor))
		{
			CRect rectWnd;
			GetWindowRect(&rectWnd);
			if (rectWnd.PtInRect(ptCursor))
			{
				ScreenToClient(&ptCursor);
				m_iHotItemIdx = CheckHotItem(ptCursor);
			}
		}
		m_pToolTip->Activate(m_iHotItemIdx >= 0 ? TRUE : FALSE);
		UpdateToolTip();

		CArray<bool> abHotItemConnected;
		if (m_iHotItemIdx >= 0)
		{
			abHotItemConnected.SetSize(iVisibleNodes);
			for (int i = 0; i < iVisibleNodes; i++)
				abHotItemConnected[i] = (m_iHotItemIdx == i);
		}
		// start drawing, beginning with the arrowClines connecting the nodes
		// if possible use GDI+ for Anti Aliasing
		extern bool g_bGdiPlusInstalled;
		ULONG_PTR gdiplusToken = 0;	
		Gdiplus::GdiplusStartupInput gdiplusStartupInput;
		if (g_bGdiPlusInstalled && Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL) == Gdiplus::Ok)
		{
			{
				Gdiplus::Graphics gdipGraphic(dc);
				gdipGraphic.SetSmoothingMode(Gdiplus::SmoothingModeAntiAlias);
				Gdiplus::AdjustableArrowCap gdipArrow(6, 4);
				Gdiplus::Pen gdipPenGray(Gdiplus::Color(192, 192, 192), 0.8f);
				gdipPenGray.SetCustomEndCap(&gdipArrow);
				Gdiplus::Pen gdipPenDarkGray(Gdiplus::Color(100, 100, 100), 0.8f);
				gdipPenDarkGray.SetCustomEndCap(&gdipArrow);
				Gdiplus::Pen gdipPenRed(Gdiplus::Color(255, 32, 32), 0.8f);
				gdipPenRed.SetCustomEndCap(&gdipArrow);

				for (int i = 0; i < iVisibleNodes; i++)
				{
					const CLookupHistory::SLookupHistoryEntry* sEntry = m_pLookupHistory->GetHistoryEntries()[m_pLookupHistory->GetHistoryEntries().GetCount() - (i + 1)];
					for (int j = 0; j < sEntry->m_liReceivedFromIdx.GetCount(); j++)
					{
						int iIdx = sEntry->m_liReceivedFromIdx[j];
						if (iIdx >= m_pLookupHistory->GetHistoryEntries().GetCount() - iVisibleNodes)
						{
							CPoint pFrom = m_aNodesDrawRects[m_pLookupHistory->GetHistoryEntries().GetCount() - (iIdx + 1)].CenterPoint();
							CPoint pointTo = m_aNodesDrawRects[i].CenterPoint();

							Gdiplus::Pen* pen;
							if (m_pLookupHistory->GetHistoryEntries().GetCount() - (iIdx + 1) == m_iHotItemIdx)
							{
								abHotItemConnected[i] = true;
								pen = &gdipPenRed;
							}
							else if (i == m_iHotItemIdx)
							{
								abHotItemConnected[m_pLookupHistory->GetHistoryEntries().GetCount() - (iIdx + 1)] = true;
								pen = &gdipPenDarkGray;
							}
							else
								pen = &gdipPenGray;

							gdipGraphic.DrawLine(pen, pFrom.x, pFrom.y, pointTo.x, pointTo.y);
						}
					}
				}
			}
			Gdiplus::GdiplusShutdown(gdiplusToken);
		}
		else
		{
			for (int i = 0; i < iVisibleNodes; i++)
			{
				const CLookupHistory::SLookupHistoryEntry* sEntry = m_pLookupHistory->GetHistoryEntries()[m_pLookupHistory->GetHistoryEntries().GetCount() - (i + 1)];
				for (int j = 0; j < sEntry->m_liReceivedFromIdx.GetCount(); j++)
				{
					int iIdx = sEntry->m_liReceivedFromIdx[j];
					if (iIdx >= m_pLookupHistory->GetHistoryEntries().GetCount() - iVisibleNodes)
					{

						CPoint pFrom = m_aNodesDrawRects[m_pLookupHistory->GetHistoryEntries().GetCount() - (iIdx + 1)].CenterPoint();
						CPoint pointTo = m_aNodesDrawRects[i].CenterPoint();

						if (m_pLookupHistory->GetHistoryEntries().GetCount() - (iIdx + 1) == m_iHotItemIdx)
						{
							abHotItemConnected[i] = true;
							dc.SelectObject(&m_penRed);
						}
						else
						{
							if (i == m_iHotItemIdx)
								abHotItemConnected[m_pLookupHistory->GetHistoryEntries().GetCount() - (iIdx + 1)] = true;
							dc.SelectObject(&m_penAux);
						}

						POINT aptPoly[3];
						POINT pBase;
						float vecLine[2];
						float vecLeft[2];
						int nWidth = 4;

						// set to point
						aptPoly[0].x = pointTo.x;
						aptPoly[0].y = pointTo.y;

						// build the line vector
						vecLine[0] = (float) aptPoly[0].x - pFrom.x;
						vecLine[1] = (float) aptPoly[0].y - pFrom.y;

						// build the arrow base vector - normal to the line
						vecLeft[0] = -vecLine[1];
						vecLeft[1] = vecLine[0];

						// setup length parameters
						float fLength = (float) sqrt(vecLine[0] * vecLine[0] + vecLine[1] * vecLine[1]);
						float th = nWidth / (2.0f * fLength);
						float ta = nWidth / (2.0f * (tanf(0.3f) / 2.0f) * fLength);

						// find the base of the arrow
						pBase.x = (int) (aptPoly[0].x + -ta * vecLine[0]);
						pBase.y = (int) (aptPoly[0].y + -ta * vecLine[1]);

						// build the points on the sides of the arrow
						aptPoly[1].x = (int) (pBase.x + th * vecLeft[0]);
						aptPoly[1].y = (int) (pBase.y + th * vecLeft[1]);
						aptPoly[2].x = (int) (pBase.x + -th * vecLeft[0]);
						aptPoly[2].y = (int) (pBase.y + -th * vecLeft[1]);
						dc.MoveTo(pFrom);
						dc.LineTo(aptPoly[0].x, aptPoly[0].y);
						dc.Polygon(aptPoly, 3);
					}
				}
			}
		}

		// draw the nodes images
		for (int i = 0; i < iVisibleNodes; i++)
		{
			CPoint pointNode = m_aNodesDrawRects[i].CenterPoint();
			pointNode.x -= 8;
			pointNode.y -= 8;

			uint8 byIconIdx = 0;
			const CLookupHistory::SLookupHistoryEntry* sEntry = m_pLookupHistory->GetHistoryEntries()[m_pLookupHistory->GetHistoryEntries().GetCount() - (i + 1)];
			if (sEntry->m_dwAskedContactsTime > 0)
			{
				if (sEntry->m_uRespondedContact > 0)
					byIconIdx = sEntry->m_bProvidedCloser ? 0 : 1; // green or blue
				else if (sEntry->m_dwAskedContactsTime + SEC2MS(3) < ::GetTickCount())
					byIconIdx = 3; // red
				else
					byIconIdx = 2; // yellow

			}
			else if (sEntry->m_bForcedInteresting)
				byIconIdx = 2;
			else
				ASSERT( false );

			if (m_iHotItemIdx >= 0 && !abHotItemConnected[i])
				m_iml.DrawEx(&dc, byIconIdx, pointNode, CSize(0, 0), CLR_NONE, GetSysColor(COLOR_WINDOW), ILD_BLEND50);
			else	
				m_iml.Draw(&dc, byIconIdx, pointNode, ILD_NORMAL);
				

			if (sEntry->m_dwAskedSearchItemTime > 0)
			{
				// Draw the Icon indicating that we asked this Node for results
				// enough space above? if not below
				CPoint pointIndicator = pointNode;
				if (pointIndicator.y - 16 - 4 >= iTopBorder)
					pointIndicator.y -= 20;
				else
					pointIndicator.y += 20;
				
				switch (m_pLookupHistory->GetType())
				{
					case Kademlia::CSearch::FILE:
					case Kademlia::CSearch::KEYWORD:
					case Kademlia::CSearch::NOTES:
					{
						int nOverlayImage = 0;
						if (sEntry->m_uRespondedSearchItem > 0)
							nOverlayImage = 1;
						else if (sEntry->m_dwAskedSearchItemTime + SEC2MS(5) < ::GetTickCount())
							nOverlayImage = 2;
						m_iml.Draw(&dc, 4, pointIndicator, ILD_NORMAL | INDEXTOOVERLAYMASK(nOverlayImage));
						break;
					}
					case Kademlia::CSearch::STOREFILE:
						m_iml.Draw(&dc, 6, pointIndicator, ILD_NORMAL);
						break;
					case Kademlia::CSearch::STOREKEYWORD:
					case Kademlia::CSearch::STORENOTES:
						m_iml.Draw(&dc, 5, pointIndicator, ILD_NORMAL);
						break;

					/* Nothing to show
					case CSearch::NODE:
					case CSearch::NODECOMPLETE:
					case CSearch::NODESPECIAL:
					case CSearch::NODEFWCHECKUDP:
					case CSearch::FINDBUDDY:
					default:*/
				}
			}
		}
	}
	m_bDbgLog = false;
	dc.SelectObject(pOldPen);
	dc.SelectObject(pOldFont);
	dc.SetTextColor(crOldTextColor);
}
Example #9
0
BOOL CSubtitleDlDlg::OnInitDialog()
{
    __super::OnInitDialog();

    m_status.Create(WS_CHILD | WS_VISIBLE | CCS_BOTTOM, CRect(0, 0, 0, 0), this, IDC_STATUSBAR);

    int n, curPos = 0;
    CArray<int> columnWidth;

    CString strColumnWidth = AfxGetApp()->GetProfileString(IDS_R_DLG_SUBTITLEDL, IDS_RS_DLG_SUBTITLEDL_COLWIDTH, _T(""));
    CString token = strColumnWidth.Tokenize(_T(","), curPos);
    while (!token.IsEmpty()) {
        if (_stscanf_s(token, L"%d", &n) == 1) {
            columnWidth.Add(n);
            token = strColumnWidth.Tokenize(_T(","), curPos);
        } else {
            throw 1;
        }
    }

    m_list.SetExtendedStyle(m_list.GetExtendedStyle()
                            | LVS_EX_DOUBLEBUFFER | LVS_EX_FULLROWSELECT
                            | LVS_EX_CHECKBOXES   | LVS_EX_LABELTIP);

    if (columnWidth.GetCount() != 5) {
        // default sizes
        columnWidth.RemoveAll();
        columnWidth.Add(290);
        columnWidth.Add(70);
        columnWidth.Add(50);
        columnWidth.Add(50);
        columnWidth.Add(270);
    }

    m_list.InsertColumn(COL_FILENAME, ResStr(IDS_SUBDL_DLG_FILENAME_COL), LVCFMT_LEFT, columnWidth[0]);
    m_list.InsertColumn(COL_LANGUAGE, ResStr(IDS_SUBDL_DLG_LANGUAGE_COL), LVCFMT_CENTER, columnWidth[1]);
    m_list.InsertColumn(COL_FORMAT, ResStr(IDS_SUBDL_DLG_FORMAT_COL), LVCFMT_CENTER, columnWidth[2]);
    m_list.InsertColumn(COL_DISC, ResStr(IDS_SUBDL_DLG_DISC_COL), LVCFMT_CENTER, columnWidth[3]);
    m_list.InsertColumn(COL_TITLES, ResStr(IDS_SUBDL_DLG_TITLES_COL), LVCFMT_LEFT, columnWidth[4]);

    AddAnchor(IDC_LIST1, TOP_LEFT, BOTTOM_RIGHT);
    AddAnchor(IDC_CHECK1, BOTTOM_LEFT);
    AddAnchor(IDOK, BOTTOM_RIGHT);
    AddAnchor(IDC_STATUSBAR, BOTTOM_LEFT, BOTTOM_RIGHT);

    const CSize s(420, 200);
    SetMinTrackSize(s);
    EnableSaveRestore(IDS_R_DLG_SUBTITLEDL);

    // set language sorting order
    const CAppSettings& settings = AfxGetAppSettings();
    CString order = settings.strSubtitlesLanguageOrder;
    // fill language->position map
    int listPos = 0;
    int tPos = 0;
    CString langCode = order.Tokenize(_T(",; "), tPos);
    while (tPos != -1) {
        CString langName = LangCodeToName(CStringA(langCode));
        if (!langName.IsEmpty()) {
            int pos;
            if (!m_defps.m_langPos.Lookup(langName, pos)) {
                m_defps.m_langPos[langName] = listPos++;
            }
        }
        langCode = order.Tokenize(_T(",; "), tPos);
    }

    // start new worker thread to download the list of subtitles
    m_pTA = DEBUG_NEW THREADSTRUCT;
    m_pTA->url = m_url;
    m_pTA->hWND = GetSafeHwnd();

    SetStatus(ResStr(IDS_SUBDL_DLG_DOWNLOADING));
    AfxBeginThread(RunThread, static_cast<LPVOID>(m_pTA));

    return TRUE;
}
Example #10
0
BOOL CDlgAddTask::ApplyDocToTaskMgr(LPCTSTR lpszLocation, BOOL & bFeedAdded, BOOL bAutoDown)
{
	// MODIFIED by VC-yavey on 2010-04-16	<begin>
	// 处理RSS订阅url
	bFeedAdded = FALSE;
	//CAddTaskDoc::RssUrlSet & setRssUrl = m_doc.GetRssUrlSet();
	CString	strCurLoc;
	m_cmbLocation.GetWindowText(strCurLoc);
	if ( !PathFileExists(strCurLoc) )
	{
		strCurLoc.Empty();
	}

	/*for ( CAddTaskDoc::RssUrlSet::const_iterator it = setRssUrl.begin();
		  it != setRssUrl.end();
		  ++it
		)
	{
 		TRACE(TEXT("\nRssUrlSet str %s\n"), *it);	
	}*/

	set<CRssFeed*>& setLastRssFeed = m_editLinks.GetLastRssFeedSet();
	for (set<CRssFeed*>::iterator it = setLastRssFeed.begin(); it != setLastRssFeed.end(); ++it )
	{
		//TRACE(TEXT("m_editLinks.m_setLastRssfee str %s\n"), (*it)->m_strFeedUrl);
		CGlobalVariable::s_wndRssCtrl->AddFeed(*it, strCurLoc, bAutoDown);
		bFeedAdded = TRUE;
	}
	// MODIFIED by VC-yavey on 2010-04-16	<end>


	//	ed2k tasks	<begin>
	const map<CFileHashKey, CAddTaskDoc::SItem>			*pMap;
	map<CFileHashKey, CAddTaskDoc::SItem>::const_iterator		it;

	CArray<SSpDownLink*, SSpDownLink*>	arrSpDownLinks;		//special download links
	CArray<SSpDownLink*, SSpDownLink*>	arrDowningLinks;	//downloading links
	CArray<SSpDownLink*, SSpDownLink*>	arrReDownLinks;		//ask whether redownload links
	CArray<SSpDownLink*, SSpDownLink*>	arrTooBigDownLinks;
	int	iState;
	CString strFileName;

	pMap = m_doc.GetData();
	for (it = pMap->begin();
		it != pMap->end();
		it++)
	{
		if (it->second.bCheck)
		{
			CED2KFileLink	*pLink = NULL;
			// MODIFIED by VC-yavey on 2010-04-16 : 安全地创建filelink
			pLink = CreateFileLinkFromUrl(it->second.strLinkText);
			if( pLink && pLink->GetSize()> OLD_MAX_EMULE_FILE_SIZE && !thePrefs.CanFSHandleLargeFiles(lpszLocation))
			{
				strFileName = CGlobalVariable::filemgr.GetFileName(it->second.strLinkText);
				SSpDownLink*	psdl = new SSpDownLink;
				psdl->iLinkType = 0;
				psdl->strLink = it->second.strLinkText;
				psdl->iCat = it->second.iCategory;
				psdl->strName = strFileName;
				arrTooBigDownLinks.Add(psdl);
				continue;
			}
			SAFE_DELETE(pLink);

			iState = CGlobalVariable::filemgr.GetFileState(it->second.strLinkText); 
			switch (iState)
			{
			case FILESTATE_DOWNLOADING:
				{
					strFileName = CGlobalVariable::filemgr.GetFileName(it->second.strLinkText);
					SSpDownLink*	psdl = new SSpDownLink;
					psdl->iLinkType = 0;
					psdl->strLink = it->second.strLinkText;
					psdl->iCat = it->second.iCategory;
					psdl->iState = iState;
					psdl->strName = strFileName;
					arrDowningLinks.Add(psdl);					
				}
				break;
			case FILESTATE_COMPLETED:
			case FILESTATE_HASH:
			case FILESTATE_DOWNLOADED_SHARE:
			case FILESTATE_LOCAL_SHARE:
			case FILESTATE_SHARE_TASK_DELED:
				{
					strFileName = CGlobalVariable::filemgr.GetFileName(it->second.strLinkText);
					SSpDownLink*	psdl = new SSpDownLink;
					psdl->iLinkType = 0;
					psdl->strLink = it->second.strLinkText;
					psdl->iCat = it->second.iCategory;
					psdl->iState = iState;
					psdl->strName = strFileName;
					arrSpDownLinks.Add(psdl);
				}
				break;
			case FILESTATE_DELETED:
				{
					strFileName = CGlobalVariable::filemgr.GetFileName(it->second.strLinkText);
					SSpDownLink*	psdl = new SSpDownLink;
					psdl->iLinkType = 0;
					psdl->strLink = it->second.strLinkText;
					psdl->iCat = it->second.iCategory;
					psdl->iState = iState;
					psdl->strName = strFileName;
					arrReDownLinks.Add(psdl);
				}
				break;
			default:
				CGlobalVariable::filemgr.NewDownloadFile(it->second.strLinkText, lpszLocation, it->second.iCategory);
				break;
			}
		}
	}
	//	ed2k tasks	<end>

	//	Url tasks	<begin>
	CString			strUrl;
	BOOL			bCheck;

	const CMapStringToPtr*	pUrlData = m_doc.GetUrlData();
	POSITION	pos = pUrlData->GetStartPosition();
	
	while (NULL != pos)
	{
		pUrlData->GetNextAssoc(pos, strUrl, (void*&)bCheck);
        
		strUrl.Trim();

		if( _tcsrchr((LPCTSTR)strUrl+7,_T('/'))==NULL )
			strUrl += _T('/');
/*
		int len=strUrl.GetLength();
		bool state=false;

		int index = strUrl.Find(_T("//"),0);
		for(int i = index + 2;i < len;i++)
		{
			if(strUrl[i] == _T('/'))
			{
				state = true;
				break;
			}
		}
		if(state ==false)
			  strUrl+='/';*/

		if (bCheck)
		{   
			iState = CGlobalVariable::filemgr.GetUrlTaskState(strUrl); //< 统一转换后再判断,避免实际是重复的Url
			switch (iState)
			{
			case FILESTATE_DOWNLOADING:   
				{
					strFileName = CGlobalVariable::filemgr.GetUrlFileName(strUrl);
					SSpDownLink*	psdl = new SSpDownLink;
					psdl->iLinkType = 1;
					psdl->strLink = strUrl;
					psdl->iCat = 0;
					psdl->iState = iState;
					psdl->strName = strFileName;
					arrDowningLinks.Add(psdl);
				}
				break;
			case FILESTATE_COMPLETED:
			case FILESTATE_HASH:
			case FILESTATE_LOCAL_SHARE:
				{
					strFileName = CGlobalVariable::filemgr.GetUrlFileName(strUrl);
					SSpDownLink*	psdl = new SSpDownLink;
					psdl->iLinkType = 1;
					psdl->strLink = strUrl;
					psdl->iCat = 0;
					psdl->iState = iState;
					psdl->strName = strFileName;
					arrSpDownLinks.Add(psdl);
				}
				break;
			case FILESTATE_DOWNLOADED_SHARE:
			case FILESTATE_SHARE_TASK_DELED:
			case FILESTATE_DELETED: 
			case FILESTATE_ZEROSIZE_DOWNLOADED:
				{
					strFileName = CGlobalVariable::filemgr.GetUrlFileName(strUrl);
					SSpDownLink*	psdl = new SSpDownLink;
					psdl->iLinkType = 1;
					psdl->strLink = strUrl;
					psdl->iCat = 0;
					psdl->iState = iState;
					psdl->strName = strFileName;
					arrReDownLinks.Add(psdl);
				}
				break;
			default:
				CmdFuncs::ActualllyAddUrlDownload(strUrl,lpszLocation);
				break;
			}
		}
	}
	//	URL tasks	<end>

	int i;

	CString strPrompt;

	if (!arrSpDownLinks.IsEmpty()) 
	{
		strPrompt = GetResString(IDS_ALREADY_DOWNLOAD);

		for (i = 0; i < arrSpDownLinks.GetCount(); i++)
		{
			if(arrSpDownLinks[i]->iLinkType==1)
				strPrompt += arrSpDownLinks[i]->strLink;
			else
				strPrompt += arrSpDownLinks[i]->strName;
			strPrompt += _T("\n");
		}
		
		for (i = 0; i < arrSpDownLinks.GetCount(); i++)
			delete arrSpDownLinks[i];
		arrSpDownLinks.RemoveAll();
	}
	
	UINT iTooBigDownLinks = 0;
	if (!arrTooBigDownLinks.IsEmpty()) 
	{
		iTooBigDownLinks =arrTooBigDownLinks.GetCount();
		if (!strPrompt.IsEmpty())
			strPrompt += _T("\n\n");
		strPrompt = GetResString(IDS_ERR_FSCANTHANDLEFILE);
		strPrompt += _T("\n");

		for (i = 0; i < arrTooBigDownLinks.GetCount(); i++)
		{
			if(arrTooBigDownLinks[i]->iLinkType==1)
				strPrompt += arrTooBigDownLinks[i]->strLink;
			else
				strPrompt += arrTooBigDownLinks[i]->strName;
			strPrompt += _T("\n");
		}

		for (i = 0; i < arrTooBigDownLinks.GetCount(); i++)
			delete arrTooBigDownLinks[i];
		arrTooBigDownLinks.RemoveAll();
	}

	if (!arrDowningLinks.IsEmpty())   
	{
		if (!strPrompt.IsEmpty())
			strPrompt += _T("\n\n");

		strPrompt += GetResString(IDS_TASK_IN_DOWNLOADING);
		for (i = 0; i < arrDowningLinks.GetCount(); i++)
		{
			if(arrDowningLinks[i]->iLinkType==1)
				strPrompt += arrDowningLinks[i]->strLink;
			else
				strPrompt += arrDowningLinks[i]->strName;
			strPrompt += _T("\n");
		}

		for (i = 0; i < arrDowningLinks.GetCount(); i++)
			delete arrDowningLinks[i];
		arrDowningLinks.RemoveAll();
	}

	if (!strPrompt.IsEmpty())
		 MessageBox(strPrompt,GetResString(IDS_CAPTION),MB_OK|MB_ICONWARNING);
	//if (IDYES == ::AfxMessageBox(strPrompt, MB_YESNO))
	//{
	//	for (i = 0; i < arrDledLink.GetCount(); i++)
	//		CGlobalVariable::filemgr.NewDownloadFile(arrDledLink[i], lpszLocation, arrDledLinkCat[i]);
	//	for (i = 0; i < arrDledUrl.GetCount(); i++)
	//		ActualllyAddUrlDownload(arrDledUrl[i], lpszLocation);
	//}

	
	if (!arrReDownLinks.IsEmpty())
	{
		strPrompt = GetResString(IDS_DOWN_DELED_LINKS);

		for (i = 0; i < arrReDownLinks.GetCount(); i++)
		{
			if(arrReDownLinks[i]->iLinkType==1)
				strPrompt += arrReDownLinks[i]->strLink;
			else
				strPrompt += arrReDownLinks[i]->strName;
			strPrompt += _T("\n");           
		}
      
		if(IDYES == MessageBox(strPrompt,GetResString(IDS_CAPTION),MB_YESNO|MB_ICONWARNING))
		{
			for (i = 0; i < arrReDownLinks.GetCount(); i++)
			{
				switch (arrReDownLinks[i]->iLinkType)
				{
				case 0:
					CGlobalVariable::filemgr.NewDownloadFile(arrReDownLinks[i]->strLink, lpszLocation, arrReDownLinks[i]->iCat);
					break;
				case 1:
					//ActualllyAddUrlDownload(arrReDownLinks[i]->strLink, lpszLocation);
					CmdFuncs::ActualllyAddUrlDownload(arrReDownLinks[i]->strLink,lpszLocation);
					break;
				default:
					break;
				}
			}
		}

		for (i = 0; i < arrReDownLinks.GetCount(); i++)
			delete arrReDownLinks[i];
		arrReDownLinks.RemoveAll();
	}
	
	if (!pMap->size() && !iTooBigDownLinks)
		return TRUE;

	return iTooBigDownLinks != pMap->size(); 
}
// 用户开户查询
void CCardopenConsumeView::QueryRegister(void)
{
	CArray<NS_DAL::CCardOpenInfo, NS_DAL::CCardOpenInfo &>  CardOpenDBArray;

	CString strSQL;

	strSQL.Append(_T("SELECT cardopen.*, member.classId, member.memberId, member.name, member.serialNum, member.idNumber  "));

	strSQL.Append(_T("FROM cardopen, member "));

	strSQL.Append(_T("WHERE  cardopen.memberId = member.memberId "));

	strSQL.Append(_T("AND  cardopen.classId = member.classId "));

	strSQL.AppendFormat(_T("AND  member.classId in %s "), GetCommonClassIdAsString());

	strSQL.AppendFormat(_T("AND cardopen.operationDateTime  BETWEEN '%s' AND '%s'")
		, m_StartTime.ToString(), m_EndTime.ToString());

	strSQL.Append(_T(" ORDER BY  cardopen.operationDateTime DESC"));

	CIBALog::GetInstance()->WriteFormat(CIBALog::ELT_SQL, _T("QueryRegister:%s"), strSQL);

	CADODBConnInfo* pDb = NULL;

	if (!CIBADAL::GetInstance()->GetDBConnInfo(pDb)) return;

	CADORecordset Rs(pDb->GetConn());

	if (Rs.Open(strSQL))
	{
		INT i = 0;

		while (!Rs.IsEof())
		{
			INT nTmp = 0;
			CString strTmp;
			CCardOpenInfo CardOpenInfo;

			Rs.GetFieldValue(_T("serialNum"), strTmp);
			CardOpenInfo.SetSerialNum(strTmp);

			Rs.GetFieldValue(_T("name"), strTmp);
			CardOpenInfo.SetUserName(strTmp);

			Rs.GetFieldValue(_T("idNumber"), strTmp);
			CardOpenInfo.SetIdNumber(strTmp);

			Rs.GetFieldValue(_T("memberId"), nTmp);
			CardOpenInfo.SetMemberId(nTmp);

			Rs.GetFieldValue(_T("operationDateTime"), strTmp);
			CardOpenInfo.SetOperationDateTime(strTmp);

			Rs.GetFieldValue(_T("operator"), strTmp);
			CardOpenInfo.SetOperator(strTmp);

			i++;
			CardOpenDBArray.Add(CardOpenInfo);
			Rs.MoveNext();
		}

		Rs.Close();
	}

	pDb->Release();

	for (INT ii = 0; ii < CardOpenDBArray.GetCount(); ii++)
	{
#ifdef _DEBUG
		if (CardOpenDBArray.GetAt(ii).GetMemberId() == 178547)
		{
			int kkk = 0;
		}
#endif

		CString strSQL;

		strSQL.Append(_T("SELECT returned.* "));

		strSQL.Append(_T("FROM returned "));

		strSQL.AppendFormat(_T("WHERE  returned.memberId = '%d' AND  returned.classId in %s  ")
			, CardOpenDBArray.GetAt(ii).GetMemberId(), GetCommonClassIdAsString());

		strSQL.AppendFormat(_T("AND returned.returnDate >=  '%s'")
			, CardOpenDBArray.GetAt(ii).GetOperationDateTime());

		strSQL.Append(_T(" ORDER BY returned.returnDate DESC"));

		CIBALog::GetInstance()->WriteFormat(CIBALog::ELT_SQL, _T("QueryReturned:%s"), strSQL);

		CADODBConnInfo* pDb = NULL;

		if (!CIBADAL::GetInstance()->GetDBConnInfo(pDb)) return;

		CADORecordset Rs(pDb->GetConn());

		if (Rs.Open(strSQL))
		{
			if (!Rs.IsEof())
			{
				CardOpenDBArray.RemoveAt(ii);
				ii--;
			}
			Rs.Close();
		}

		pDb->Release();
	}

	for (INT jj = 0; jj < CardOpenDBArray.GetCount(); jj++)
	{
		INT nTmp = 0;
		CString strTmp;

		m_InfoList.InsertItem(jj, CardOpenDBArray.GetAt(jj).GetSerialNum());

		m_InfoList.SetItemText(jj, 1, CardOpenDBArray.GetAt(jj).GetUserName());

		m_InfoList.SetItemText(jj, 3, CardOpenDBArray.GetAt(jj).GetIdNumber());

		strTmp.Format(_T("%d"), CardOpenDBArray.GetAt(jj).GetMemberId());
		m_InfoList.SetItemText(jj, 4, strTmp);

		m_InfoList.SetItemText(jj, 5, CardOpenDBArray.GetAt(jj).GetOperationDateTime());
	}
	CardOpenDBArray.RemoveAll();
}
Example #12
0
void CServer::LoadData()
{
	for (int i =0; i < g_LedInfos.GetCount(); i++)
	{
		delete g_LedInfos.GetAt(i);
	}
	g_LedInfos.RemoveAll();

	_RecordsetPtr rs = g_DB.GetRecordset(_T("SELECT * FROM LEDInfo"));
	while(!rs->adoEOF)
	{
		LED_INFO *pLedInfo = new LED_INFO;
		CString sTemp;
		if (rs->GetCollect(_T("Address")).vt != VT_NULL)
		{
			pLedInfo->sAddress = (LPCSTR)(_bstr_t)rs->GetCollect(_T("Address"));
		}

		if (rs->GetCollect(_T("Groups")).vt != VT_NULL)
		{
			pLedInfo->sGroups = (LPCSTR)(_bstr_t)rs->GetCollect(_T("Groups"));
		}

		if (rs->GetCollect(_T("Direction")).vt != VT_NULL)
		{
			pLedInfo->sDirection = (LPCSTR)(_bstr_t)rs->GetCollect(_T("Direction"));
		}

		if (rs->GetCollect(_T("ParkingLotNum")).vt != VT_NULL)
		{
			pLedInfo->uParkingLotNum = _ttoi((LPCSTR)(_bstr_t)rs->GetCollect(_T("ParkingLotNum")));
		}

		if (rs->GetCollect(_T("TextFormat")).vt != VT_NULL)
		{
			pLedInfo->sTextRgb = (LPCSTR)(_bstr_t)rs->GetCollect(_T("TextFormat"));
			
		}

		if (rs->GetCollect(_T("TagFormat")).vt != VT_NULL)
		{
			pLedInfo->sTagRgb = (LPCSTR)(_bstr_t)rs->GetCollect(_T("TagFormat"));
		}

		if (rs->GetCollect(_T("ComNum")).vt != VT_NULL)
		{
			pLedInfo->nComNum = _ttoi((LPCSTR)(_bstr_t)rs->GetCollect(_T("ComNum")));
		}

		g_LedInfos.Add(pLedInfo);
		rs->MoveNext();
	}
	rs->Close();

	g_bLedChange = FALSE;

	//rs = g_DB.GetRecordset(_T("SELECT * FROM GroupInfo"));
	//while(!rs->adoEOF)
	//{
	//	GROUP_INFO *pGroupInfo = new GROUP_INFO;
	//	CString sTemp;
	//	if (rs->GetCollect(_T("GroupID")).vt != VT_NULL)
	//	{
	//		pGroupInfo->sGroupID = (LPCSTR)(_bstr_t)rs->GetCollect(_T("GroupID"));
	//	}

	//	if (rs->GetCollect(_T("LedAddress")).vt != VT_NULL)
	//	{
	//		pGroupInfo->sLedAddress = (LPCSTR)(_bstr_t)rs->GetCollect(_T("LedAddress"));
	//	}

	//	if (rs->GetCollect(_T("Effective")).vt != VT_NULL)
	//	{
	//		pGroupInfo->nEffective = _ttoi((LPCSTR)(_bstr_t)rs->GetCollect(_T("Effective")));
	//	}

	//	if (rs->GetCollect(_T("RedLightNum")).vt != VT_NULL)
	//	{
	//		pGroupInfo->nRedLightNum = _ttoi((LPCSTR)(_bstr_t)rs->GetCollect(_T("RedLightNum")));

	//	}

	//	if (rs->GetCollect(_T("GreenLightNum")).vt != VT_NULL)
	//	{
	//		pGroupInfo->nGreenLightNum = _ttoi((LPCSTR)(_bstr_t)rs->GetCollect(_T("GreenLightNum")));
	//	}

	//	if (rs->GetCollect(_T("RGLightNum")).vt != VT_NULL)
	//	{
	//		pGroupInfo->nRGLightNum = _ttoi((LPCSTR)(_bstr_t)rs->GetCollect(_T("RGLightNum")));
	//	}

	//	if (rs->GetCollect(_T("NoneLightNum")).vt != VT_NULL)
	//	{
	//		pGroupInfo->nNoneLightNum = _ttoi((LPCSTR)(_bstr_t)rs->GetCollect(_T("NoneLightNum")));
	//	}

	//	g_GroupInfos.Add(pGroupInfo);
	//	rs->MoveNext();
	//}
	//rs->Close();
}
Example #13
0
void CServer::STCPRecvThread(LPVOID pParam)
{
	clientdata *pcdata = (clientdata *)pParam;
	// 循环接收client端的连接请求
	char g_szBuff[MAX_PACKET_SIZE + 1];

	while(g_bAppRun)
	{
		memset(g_szBuff, 0, sizeof(g_szBuff));
		int nRecv = ::recv(pcdata->sClient, g_szBuff, MAX_PACKET_SIZE + 1, 0);
		if (nRecv == 0 || nRecv == SOCKET_ERROR)
		{
			TCHAR("客服端关闭");
			break;
		}
		if (nRecv > 0)
		{
			g_szBuff[nRecv] = '\0';
		}

		// 解析命令
		CCSDef::TMSG_HEADER* pMsgHeader = (CCSDef::TMSG_HEADER*)g_szBuff;

		switch (pMsgHeader->cMsgID)
		{
		case MSG_LEDINFO: 
			{
				//OpenFileError(pMsgHeader);
			}
			break;
		case MSG_DEVICEINFO:
			{
				CCSDef::TMSG_GROUPINFO* pGroupInfoMsg = (CCSDef::TMSG_GROUPINFO*)pMsgHeader;

				//添加或修改设备信息
				DEVICE_INFO *DeviceInfo = NULL;
				BOOL bFlag = FALSE;
				for (int i = 0; i < g_DeviceInfos.GetCount(); i++)
				{
					if(g_DeviceInfos.GetAt(i)->sIP == inet_ntoa(pcdata->ClientAddr.sin_addr))
					{
						DeviceInfo = g_DeviceInfos.GetAt(i);
						bFlag = TRUE;
					}
				}
				if (!bFlag)
				{
					DeviceInfo = new DEVICE_INFO;
					DeviceInfo->sIP = inet_ntoa(pcdata->ClientAddr.sin_addr);
					g_DeviceInfos.Add(DeviceInfo);
				}

				//添加或修改组信息
				GROUP_INFO *GroupInfo = NULL;
				bFlag = FALSE;
				for (int i = 0; i < DeviceInfo->aGroupInfos.GetCount(); i++)
				{
					if(DeviceInfo->aGroupInfos.GetAt(i)->sGroupID == pGroupInfoMsg->szGroupID)
					{
						GroupInfo = DeviceInfo->aGroupInfos.GetAt(i);
						bFlag = TRUE;
					}
				}
				if (!bFlag)
				{
					GroupInfo = new GROUP_INFO;
					GroupInfo->sGroupID = pGroupInfoMsg->szGroupID;
					DeviceInfo->aGroupInfos.Add(GroupInfo);
				}
				GroupInfo->nEffective = 1;
				GroupInfo->nGreenLightNum = pGroupInfoMsg->nGreenLightNum;
				GroupInfo->nNoneLightNum = pGroupInfoMsg->nNoneLightNum;
				GroupInfo->nRedLightNum = pGroupInfoMsg->nRedLightNum;
				GroupInfo->nRGLightNum = pGroupInfoMsg->nRGLightNum;

				//nRedLightNum = 0;
				//nGreenLightNum = 0;
				//nRGLightNum = 0;
				//nNoneLightNum = 0;
				////遍历设备中与该组相关的信息
				//for (int i = 0; i < g_DeviceInfos.GetCount(); i++)
				//{
				//	DeviceInfo = g_DeviceInfos.GetAt(i);
				//	for (int j = 0; j < DeviceInfo->aGroupInfos.GetCount(); j++)
				//	{
				//		GroupInfo = DeviceInfo->aGroupInfos.GetAt(j);
				//		if (GroupInfo->sGroupID == pGroupInfoMsg->szGroupID)
				//		{
				//			nRedLightNum += GroupInfo->nRedLightNum;
				//			nGreenLightNum += GroupInfo->nGreenLightNum;
				//			nNoneLightNum += GroupInfo->nNoneLightNum;
				//			nRGLightNum += GroupInfo->nRGLightNum;
				//		}
				//	}
				//}

				//CString sSql;
				//sSql.Format(_T("UPDATE GroupInfo SET RedLightNum = %d, GreenLightNum = %d, NoneLightNum = %d, RGLightNum = %d WHERE GroupID = '%s'"),
				//	nRedLightNum, nGreenLightNum, nNoneLightNum, nRGLightNum, pGroupInfoMsg->szGroupID);
				//g_DB.ExecuteSQL((_bstr_t)sSql);
			}
			break;
		}
	}

	::closesocket(pcdata->sClient);
	delete pcdata;
	pcdata = NULL;
}
Example #14
0
void CServer::BroadcastThread(LPVOID pParam)
{
	int i, j, k;
	LED_INFO *pLedInfo;
	CString str1, str2;
	CString sSql;
	int nTem;

	int nRedLightNum;
	int nGreenLightNum;
	int nRGLightNum;
	int nNoneLightNum;

	DEVICE_INFO *DeviceInfo = NULL;
	GROUP_INFO *GroupInfo = NULL;

	CString s1, s2;
	int nS1 = 0, nS2 = 0;

	while(g_bAppRun)
	{
		//如果数据改变则重新加载
		if (g_bLedChange)
			LoadData();

		// 把数据广播出去
		CCSDef::TMSG_LEDINFO tMsgLedInfo;
		for (i = 0; i < g_LedInfos.GetCount(); i++)
		{
			pLedInfo = g_LedInfos.GetAt(i);

			nRedLightNum = 0;
			nGreenLightNum = 0;
			nRGLightNum = 0;
			nNoneLightNum = 0;
			if (pLedInfo->sGroups != "")
			{
				nS1 = 0;
				while(AfxExtractSubString(s1, pLedInfo->sGroups, nS1, ';'))
				{
					//遍历设备中与该组相关的信息
					for (j = 0; j < g_DeviceInfos.GetCount(); j++)
					{
						DeviceInfo = g_DeviceInfos.GetAt(j);
						for (k = 0; k < DeviceInfo->aGroupInfos.GetCount(); k++)
						{
							GroupInfo = DeviceInfo->aGroupInfos.GetAt(k);
							if (GroupInfo->sGroupID == s1)
							{
								nRedLightNum += GroupInfo->nRedLightNum;
								nGreenLightNum += GroupInfo->nGreenLightNum;
								nNoneLightNum += GroupInfo->nNoneLightNum;
								nRGLightNum += GroupInfo->nRGLightNum;
							}
						}
					}
					nS1++;
				}
			}
			
			//nRedNum = 0;
			//sSql.Format(_T("SELECT SUM(RedLightNum) AS RedLightNum1 FROM GroupInfo WHERE LedAddress = '%s'"), pLedInfo->sAddress);
			//_RecordsetPtr rs = g_DB.GetRecordset((_bstr_t)sSql);
			//while(!rs->adoEOF)
			//{
			//	if (rs->GetCollect(_T("RedLightNum1")).vt != VT_NULL)
			//	{
			//		nTem = _ttoi((LPCSTR)(_bstr_t)rs->GetCollect(_T("RedLightNum1")));
			//		if (nTem > 0)
			//		{
			//			nRedNum += nTem;
			//		}
			//	}
			//	rs->MoveNext();
			//}
			//rs->Close();

			nTem = pLedInfo->uParkingLotNum - nRedLightNum;

			str1.Format(_T("%s@%s@%d@%s@%s@%d"), pLedInfo->sAddress, pLedInfo->sDirection,
				nTem > 0 ? nTem : 0, pLedInfo->sTextRgb, pLedInfo->sTagRgb, pLedInfo->nComNum);
			if (i == 0)
			{
				str2 = str1;
			}else
			{
				str2 += _T("$") + str1;
			}
		}
		strcpy(tMsgLedInfo.szBuff, str2);

		SOCKADDR_IN dstAdd; 
		dstAdd.sin_family = AF_INET; 
		dstAdd.sin_port = htons(CAST_PORT);
		dstAdd.sin_addr.s_addr = INADDR_BROADCAST;
		if(SOCKET_ERROR == ::sendto(g_sCastSend, (char*)(&tMsgLedInfo), sizeof(CCSDef::TMSG_GROUPINFO), 0, (SOCKADDR*)&dstAdd, sizeof(SOCKADDR)))
		{
			TRACE("Send Data Error!\n");
			return;
		}
		Sleep(800);
	}
}
Example #15
0
/*-----------------------------------------CIRexxApp::initializeIndexDatabase-+
|                                                                             |
+----------------------------------------------------------------------------*/
void CIRexxApp::initializeIndexDatabase()
{
   m_isScriptIndexDBInitialized = true;

   Err err;
   char categoryName[dmCategoryLength];

   // Open MemoPad's DB as a source for scripts.
   m_memoDB = new CDatabase(
      0, "MemoDB", sysFileCMemo, 'data', false, false, dmModeReadOnly
   );
   for (m_memoCategory = 0; m_memoCategory < dmRecNumCategories; ++m_memoCategory) {
       CategoryGetName(m_memoDB->GetDatabasePtr(), m_memoCategory, categoryName);
       if (!StrCaselessCompare(categoryName, "REXX")) { break; }
   }
   if (m_memoCategory == dmRecNumCategories ||
       m_memoDB->NumRecordsInCategory(m_memoCategory) == 0) {
       delete m_memoDB;
       m_memoDB = 0;
   }

   //<<<JAL TODO:  I think CategoryGetName() will core dump
   // if the db has no categories.  So, we should probably
   // check the db attrs before doing this.


   // Open pedit's DB as a source for scripts.
   // Since this DB may not exist (unlike MmeoPad's)
   // then Open() or CategoryGetName() may throw an exception
   // that we'll have to handle properly.
   try {
      m_pedit32DB = new CDatabase();
      err = m_pedit32DB->Open(0, "Memo32DB", dmModeReadOnly);
      for (m_pedit32Category = 0; m_pedit32Category < dmRecNumCategories; ++m_pedit32Category) {
          CategoryGetName(m_pedit32DB->GetDatabasePtr(), m_pedit32Category, categoryName);
          if (!StrCaselessCompare(categoryName, "REXX")) { break; }
      }
      if (m_pedit32Category == dmRecNumCategories ||
          m_pedit32DB->NumRecordsInCategory(m_pedit32Category) == 0) {
         delete m_pedit32DB;
         m_pedit32DB = 0;
      }
   } catch (...) {
       delete m_pedit32DB;
       m_pedit32DB = 0;
   }

   // Open our own DB as a source for scripts.
   try {
      m_rexxDB = new CDatabase();
      err = m_rexxDB->Open(0, "RexxDB", dmModeReadOnly);
      for (m_rexxCategory = 0; m_rexxCategory < dmRecNumCategories; ++m_rexxCategory) {
          CategoryGetName(m_rexxDB->GetDatabasePtr(), m_rexxCategory, categoryName);
          if (!StrCaselessCompare(categoryName, "REXX")) { break; }
      }
      if (m_rexxCategory == dmRecNumCategories ||
          m_rexxDB->NumRecordsInCategory(m_rexxCategory) == 0) {
         delete m_rexxDB;
         m_rexxDB = 0;
      }
   } catch (...) {
       delete m_rexxDB;
       m_rexxDB = 0;
   }

   if (m_memoDB == 0 && m_pedit32DB == 0 && m_rexxDB == 0) { return; }

   // Create an index and then index each database so that we can
   // serialize the index into a actual POL database for grid mapping.
   CArray<ScriptRecord *> records;

   addRecordsToIndex(records, m_pedit32DB, m_pedit32Category, "P");
   addRecordsToIndex(records, m_memoDB, m_memoCategory, "M");
   addRecordsToIndex(records, m_rexxDB, m_rexxCategory, "R");

   m_scriptIndexDB = new CDatabase(0, "RexxScriptIndexDB", CREATORID, 'temp');
   m_scriptIndexDB->RemoveAllRecords();
   for (int i = 0; i < records.GetCount(); ++i) {
      ScriptRecord * sr = records[i];
      CRecordStream rs(m_scriptIndexDB);
      rs << sr->m_title;  //<<<JAL TODO:  YUCK!  MOVE ACCESS TO ScriptRecord CLASS!
      rs << sr->m_dbi;
      rs << (UInt32)sr->m_db;
      rs << sr->m_indexes.GetCount();
      for (int j = 0; j < sr->m_indexes.GetCount(); ++j) {
         rs << sr->m_indexes[j] << sr->m_segments[j];
      }
   }
   for (int i = 0; i < records.GetCount(); ++i) {
      delete records[i];
   }
   return;
}
Example #16
0
char* CHSDownloadData::MakeReqPacket( CodeInfo* pCode, short nPeriod , long &lReqLen)
{
	if ( pCode == NULL || IsBadReadPtr(pCode,1))
		return NULL;
	BOOL bChangeRange = FALSE;
	BOOL bDownLoaded = FALSE;
	CString str;
	str.Format("%d-%s",pCode->m_cCodeType,pCode->GetCode());
/*	TaskItem* m_pTaskItem = NULL;*/
	if( m_pTaskItem && !IsBadReadPtr(m_pTaskItem,1) && m_pTaskItem->m_TaskName.Compare(str) )
	{
		m_pTaskItem->SetDayTaskFinished();
		m_pTaskItem->SetMinute1TaskFinished();
		m_pTaskItem->SetMinute5TaskFinished();
		return NULL;
	}

	m_DownLoadCount = 0;
	int nAfterBegin = 1300,nAfterEnd = 1500;
	short nGZIndex = MakeGZIndex(pCode->m_cCodeType);
	short nQihuo = MakeMarket(pCode->m_cCodeType);
	if (nQihuo == FUTURES_MARKET)
	{
		if (nGZIndex)
		{
			nAfterEnd = 1515;
		}
		else
		{
			nAfterBegin = 1330;
		}
	}
	//取本地缓存中已有的数据
	GetLocalData(pCode,nPeriod,m_pTaskItem);

	CArray<DateRange,DateRange> ayDate;
	CTime t1 = GetNowTime(nPeriod);
	CTimeSpan tSpan = GetTimeStep(nPeriod);
	unsigned long nLimitTime = GetLimitDate(pCode,nPeriod,m_nLimitedDay);//修正2012时间问题
	unsigned long nEarliestTime = GetIntTimeFromTime(t1,nPeriod);//修正2012时间问题
	unsigned long nTodayTime = nEarliestTime;//修正2012时间问题

	long lCurDate = 10;	
	
	CTime tmNow = CTime::GetCurrentTime();
	lCurDate = tmNow.GetYear() * 10000 + tmNow.GetMonth() * 100 + tmNow.GetDay();
	
	bDownLoaded = IsDownLoaded(lCurDate,pCode,nPeriod);

	try
	{

		BOOL bExistLastData = FALSE;
		BOOL bFirstDayRange = TRUE;
		CString strCode = pCode->GetCode();
		StockDay* pStockDay = (StockDay*)m_pTaskItem->m_localData;
		for(int i =  m_pTaskItem->m_localDataCount - 1; i >= 0; i--)
		{
			if (bDownLoaded)
			{
				break;
			}

			if(pStockDay[i].m_lDate <= 0)
				continue;

			if(pStockDay[i].m_lDate < nEarliestTime)
				nEarliestTime = pStockDay[i].m_lDate;

			if (pStockDay[i].m_lDate == 20000000) //修正错误的日期时间
			{
				pStockDay[i].m_lDate = 19991231;
			}

			///////////////若本地一存在的数据日期在限制时间内 则挑过数据的缺失检查/////////////////////////////
			if (i == m_pTaskItem->m_localDataCount - 1)
			{
				CTime tmNow = t1;
				CTime tmLastData = GetTimeFromIntTime(pStockDay[i].m_lDate,nPeriod);
				int nNowYear = tmNow.GetYear();
				int nNowMonth = tmNow.GetMonth();
				int nNowDay = tmNow.GetDay();
				if ( nNowYear == tmLastData.GetYear() && nNowMonth == tmLastData.GetMonth() && tmLastData.GetDay() == nNowDay)
				{
					CTime tmlimit = GetTimeFromIntTime(nLimitTime,nPeriod);
					CTime tmFirstDate = GetTimeFromIntTime(pStockDay[0].m_lDate,nPeriod);
					if (m_nLimitedDay == 0)
					{
						if ( PERIOD_TYPE_DAY != nPeriod)
						{
							int nMaxDays = 0;
							if (nGZIndex)
								nMaxDays = 36 - 1;  //36 = (10000/240 * 240)/270
							else
								nMaxDays = 41 - 1; //41= 10000/240

							long lLastDate = tmLastData.GetYear() * 10000 + tmLastData.GetMonth() * 100 + tmLastData.GetDay();
						
							if (lLastDate != lCurDate)
							{
								nMaxDays --;
							}

							CTimeSpan tmSpan(1,0,0,0);
							int nCount = 0;
							while(nCount < nMaxDays)
							{
								tmLastData -= tmSpan;
								if (tmLastData.GetDayOfWeek() != 1&& tmLastData.GetDayOfWeek() != 7)
								{
									nCount ++;
								}
							}				
						}
						if (PERIOD_TYPE_DAY == nPeriod)
						{
							if (tmFirstDate.GetYear() <= tmlimit.GetYear() && tmFirstDate.GetMonth() <= tmlimit.GetMonth() 
								&& tmFirstDate.GetDay() <= tmlimit.GetDay())
							{
								bExistLastData = TRUE;
							}
						}
						else if (tmFirstDate.GetYear() <= tmLastData.GetYear() && tmFirstDate.GetMonth() <= tmLastData.GetMonth() 
							&& tmFirstDate.GetDay() <= tmLastData.GetDay())
						{
							bExistLastData = TRUE;
						}
					}
					else
					{
						if (tmFirstDate.GetYear() <= tmlimit.GetYear() && tmFirstDate.GetMonth() <= tmlimit.GetMonth() 
							&& tmFirstDate.GetDay() <= tmlimit.GetDay())
						{
							bExistLastData = TRUE;
						}
					}
					if (bExistLastData)
					{
						break;
					}
				}
			}
			//////////////////////////////////////////////////////////////////////////

			int nCount = 0;	
			long lEndDate = 0;
			long lBeginDate = 0;

			CTime t2 = GetTimeFromIntTime(pStockDay[i].m_lDate,nPeriod);
			CTime t = t2;
			if (i != m_pTaskItem->m_localDataCount - 1)
			{
				t = t + tSpan;
			}
			while(t < t1)
			{
				if(t.GetDayOfWeek() != 1 &&  t.GetDayOfWeek() != 7 && t < t1) //1 = Sunday, 2 = Monday, ..., 7 = Saturday
				{
					if(lBeginDate == 0)
						lBeginDate = GetIntTimeFromTime(t,nPeriod);

					if (!bFirstDayRange)
					{
						lEndDate = GetIntTimeFromTime(t1 - tSpan,nPeriod);
					}
					else
					{
						while(t1.GetDayOfWeek()==1 || t1.GetDayOfWeek() == 7)
						{
							CTimeSpan OneDay(1,0,0,0);
							t1 -= OneDay;
						}
						lEndDate = GetIntTimeFromTime(t1,nPeriod);
					}
					nCount ++;
					break;
				}
				t = t + tSpan;
			};

			t1 = t2;
			bFirstDayRange = FALSE;

			if(nCount > 0 && lBeginDate >= nLimitTime )
			{
				if( lEndDate < nLimitTime)
					lEndDate = nLimitTime;

				CTime tmBegin = GetTimeFromIntTime(lBeginDate,nPeriod);
				CTime tmEnd = GetTimeFromIntTime(lEndDate,nPeriod);
				if (tmBegin.GetYear() == tmEnd.GetYear() && tmBegin.GetMonth() == tmEnd.GetMonth() && tmBegin.GetDay() == tmEnd.GetDay())
				{
					if (tmBegin.GetHour()*100 + tmBegin.GetMinute() > 1130 && tmEnd.GetHour()*100 + tmEnd.GetMinute() < nAfterBegin)
					{
						continue;
					}
				}

				if (lBeginDate > lEndDate)
				{
					continue ;
				}

				DateRange dr;
				dr.m_nBeginDate = lBeginDate;
				dr.m_nEndDate = lEndDate;
				ayDate.Add(dr);
			}

			if (nCount == 0 && pStockDay[i].m_lDate <= nLimitTime)
			{
				break;
			}
		}

		//下载分钟线数据时按9840的倍数根往前下载,若没有最近41天的数据,则下载最近82天数据,依次类推,最多倒退41*18天
		int nLimitedDays = 0,nPermitCount = 9840;
		if (ayDate.GetCount() < 1)
		{
			if(nEarliestTime > nLimitTime && !bExistLastData) 			//加入最后一段时间
			{
				DateRange dr;
				dr.m_nBeginDate = nLimitTime;
				dr.m_nEndDate = nEarliestTime;
				ayDate.Add(dr);
			}
		}
		else
		{
			int nMaxDays = 0;
			DateRange LastDateRage = ayDate.GetAt(ayDate.GetUpperBound());
			long nPreDate = GetPreDataDate(pCode,LastDateRage.m_nBeginDate,nPeriod);
			if (nGZIndex)
				nMaxDays = 36 - 1;  //36 = (10000/240 * 240)/270
			else
				nMaxDays = 41 - 1;  //41= 10000/240

			long nEarlyLimitedDate = nLimitTime;
			if (PERIOD_TYPE_DAY != nPeriod)
			{
				nEarlyLimitedDate = GetPreDate(pStockDay[m_pTaskItem->m_localDataCount -1].m_lDate,nMaxDays,nPeriod);
				long nCheckDataCount = GetDayDataCount(pCode,nEarlyLimitedDate,nTodayTime,nPeriod);
				if (nCheckDataCount > nPermitCount)
				{
					int nSurplusCount = nCheckDataCount - nPermitCount;
					nEarlyLimitedDate = GetChangedBeginDate(pCode,nEarlyLimitedDate,nSurplusCount,nPeriod);
				}
			}
			if (nPreDate >= nEarlyLimitedDate)
			{
				DateRange dr;
				dr.m_nBeginDate = nEarlyLimitedDate > nLimitTime ? nEarlyLimitedDate : nLimitTime;
				dr.m_nEndDate = nPreDate;
				ayDate.Add(dr);
			}
		}

		CArray<DateRange,DateRange> ayDateChange;
		int nDateCount = ayDate.GetCount();
		nPermitCount = nPermitCount*(m_nReloadDegree + 1);
		for (int i = nDateCount - 1; i>= 0; i--)
		{
			DateRange dateRange = ayDate.GetAt(i);
			long nRangeCount = GetDayDataCount(pCode,dateRange.m_nBeginDate,dateRange.m_nEndDate,nPeriod);
			nLimitedDays += nRangeCount;
			if (nLimitedDays < nPermitCount)
			{
				ayDateChange.Add(dateRange);
			}
			else
			{
				int nSpillCount = nLimitedDays - nPermitCount;
				dateRange.m_nBeginDate = GetChangedBeginDate(pCode,dateRange.m_nBeginDate,nSpillCount,nPeriod);
				ayDateChange.Add(dateRange);
				bChangeRange = TRUE;
				break;
			}
		}
		if (bChangeRange)
		{
			nDateCount = ayDateChange.GetCount();
		}

		if (bDownLoaded)
		{
			bChangeRange = TRUE;
			ayDateChange.RemoveAll();
			long nOutRangeDateB = 20101001; //国庆放假无交易行情
			long nOutRangeDateE = 20101001;
			if (PERIOD_TYPE_DAY != nPeriod)
			{
				nOutRangeDateB = 2010010930;
				nOutRangeDateE = 2010010930;
			}		
			DateRange dr;
			dr.m_nBeginDate = nOutRangeDateB;
			dr.m_nEndDate = nOutRangeDateE;
			nDateCount = ayDateChange.GetCount();
		}

		short nCount = sizeof(ReqDayData) / sizeof(CodeInfo);
		if( sizeof(ReqDayData) % sizeof(CodeInfo) )
			nCount++;
		int lLen = sizeof(AskData) + sizeof(CodeInfo) * (nCount - 1) + nDateCount * sizeof(DateRange);
		lReqLen = lLen;
		AskData* ask = (AskData*)(new char[lLen]);
		memset(ask,0,lLen);

		ask->m_nType  = RT_TECHDATA_RANGE;
		ask->m_nSize  = nCount;
		ask->m_lKey = nPeriod;
		memcpy(&ask->m_nPrivateKey, pCode, sizeof(CodeInfo));

		ReqRangeDayData* pRequest = (ReqRangeDayData*)ask->m_pCode;
		pRequest->m_lBeginPosition = 0;
		pRequest->m_nDay = 0;
		pRequest->m_cPeriod = nPeriod;
		memcpy(&pRequest->m_ciCode, pCode, sizeof(CodeInfo));
		pRequest->m_nDataRangCount = nDateCount;
		DateRange *pRane = pRequest->m_dataRange;

		CString strRequest,strRang;
		for(int nIndex = 0; nIndex < nDateCount; nIndex++)
		{
			if (bChangeRange)
				pRane[nIndex] = ayDateChange.GetAt(nIndex);
			else
				pRane[nIndex] = ayDate.GetAt(nIndex);

			m_DownLoadCount += GetDayDataCount(pCode,pRane[nIndex].m_nBeginDate,pRane[nIndex].m_nEndDate,nPeriod);
			strRang.Format("%d-%d;",pRane[nIndex].m_nBeginDate,pRane[nIndex].m_nEndDate);
			strRequest += strRang;
		}
		return (char*)ask;

	}
	catch (...)
	{
	}
	return NULL;
}
Example #17
0
void CCorruptionBlackBox::CorruptedData(uint32 nStartPos, uint32 nEndPos){
	if (nEndPos - nStartPos >= EMBLOCKSIZE){
		ASSERT( false );
		return;
	}
	// convert pos to relative block pos
	uint16 nPart = nStartPos / PARTSIZE;
	uint32 nRelStartPos = nStartPos - nPart*PARTSIZE;
	uint32 nRelEndPos = nEndPos - nPart*PARTSIZE;
	if (nRelEndPos >= PARTSIZE){
		ASSERT( false );
		return;
	}
	if (nPart >= m_aaRecords.GetCount()){
		//ASSERT( false );
		m_aaRecords.SetSize(nPart+1);
	}
	uint32 nDbgVerifiedBytes = 0;
	CArray<uint32, uint32> aGuiltyClients;
	for (int i= 0; i < m_aaRecords[nPart].GetCount(); i++){
		if (m_aaRecords[nPart][i].m_BBRStatus == BBR_NONE){
			if (m_aaRecords[nPart][i].m_nStartPos >= nRelStartPos && m_aaRecords[nPart][i].m_nEndPos <= nRelEndPos){
				nDbgVerifiedBytes +=  (m_aaRecords[nPart][i].m_nEndPos-m_aaRecords[nPart][i].m_nStartPos)+1;
				m_aaRecords[nPart][i].m_BBRStatus = BBR_CORRUPTED;
				aGuiltyClients.Add(m_aaRecords[nPart][i].m_dwIP);
			}
			else if (m_aaRecords[nPart][i].m_nStartPos < nRelStartPos && m_aaRecords[nPart][i].m_nEndPos > nRelEndPos){
			    // need to split it 2*
				uint32 nTmpEndPos1 = m_aaRecords[nPart][i].m_nEndPos;
				uint32 nTmpStartPos1 = nRelEndPos + 1;
				uint32 nTmpStartPos2 = m_aaRecords[nPart][i].m_nStartPos;
				uint32 nTmpEndPos2 = nRelStartPos - 1;
				m_aaRecords[nPart][i].m_nEndPos = nRelEndPos;
				m_aaRecords[nPart][i].m_nStartPos = nRelStartPos;
				m_aaRecords[nPart].Add(CCBBRecord(nTmpStartPos1, nTmpEndPos1, m_aaRecords[nPart][i].m_dwIP, m_aaRecords[nPart][i].m_BBRStatus));
				m_aaRecords[nPart].Add(CCBBRecord(nTmpStartPos2, nTmpEndPos2, m_aaRecords[nPart][i].m_dwIP, m_aaRecords[nPart][i].m_BBRStatus));
				nDbgVerifiedBytes +=  (m_aaRecords[nPart][i].m_nEndPos-m_aaRecords[nPart][i].m_nStartPos)+1;
				m_aaRecords[nPart][i].m_BBRStatus = BBR_CORRUPTED;
				aGuiltyClients.Add(m_aaRecords[nPart][i].m_dwIP);
			}
			else if (m_aaRecords[nPart][i].m_nStartPos >= nRelStartPos && m_aaRecords[nPart][i].m_nStartPos <= nRelEndPos){
				// need to split it
				uint32 nTmpEndPos = m_aaRecords[nPart][i].m_nEndPos;
				uint32 nTmpStartPos = nRelEndPos + 1;
				m_aaRecords[nPart][i].m_nEndPos = nRelEndPos;
				m_aaRecords[nPart].Add(CCBBRecord(nTmpStartPos, nTmpEndPos, m_aaRecords[nPart][i].m_dwIP, m_aaRecords[nPart][i].m_BBRStatus));
				nDbgVerifiedBytes +=  (m_aaRecords[nPart][i].m_nEndPos-m_aaRecords[nPart][i].m_nStartPos)+1;
				m_aaRecords[nPart][i].m_BBRStatus = BBR_CORRUPTED;
				aGuiltyClients.Add(m_aaRecords[nPart][i].m_dwIP);
			}
			else if (m_aaRecords[nPart][i].m_nEndPos >= nRelStartPos && m_aaRecords[nPart][i].m_nEndPos <= nRelEndPos){
				// need to split it
				uint32 nTmpStartPos = m_aaRecords[nPart][i].m_nStartPos;
				uint32 nTmpEndPos = nRelStartPos - 1;
				m_aaRecords[nPart][i].m_nStartPos = nRelStartPos;
				m_aaRecords[nPart].Add(CCBBRecord(nTmpStartPos, nTmpEndPos, m_aaRecords[nPart][i].m_dwIP, m_aaRecords[nPart][i].m_BBRStatus));
				nDbgVerifiedBytes +=  (m_aaRecords[nPart][i].m_nEndPos-m_aaRecords[nPart][i].m_nStartPos)+1;
				m_aaRecords[nPart][i].m_BBRStatus = BBR_CORRUPTED;
				aGuiltyClients.Add(m_aaRecords[nPart][i].m_dwIP);
			}
		}
	}
	// check if any IPs are already banned, so we can skip the test for those
	for(int k = 0; k < aGuiltyClients.GetCount();){
		// remove doubles
		for(int y = k+1; y < aGuiltyClients.GetCount();){
			if (aGuiltyClients[k] == aGuiltyClients[y])
				aGuiltyClients.RemoveAt(y);
			else
				y++;
		}
		if (theApp.clientlist->IsBannedClient(aGuiltyClients[k])){
			AddDebugLogLine(DLP_DEFAULT, false, _T("CorruptionBlackBox: Suspicous IP (%s) is already banned, skipping recheck"), ipstr(aGuiltyClients[k]));
			aGuiltyClients.RemoveAt(k);
		}
		else
			k++;
	}
	AddDebugLogLine(DLP_HIGH, false, _T("Found and marked %u recorded bytes of %u as corrupted in the CorruptionBlackBox records, %u clients involved"), nDbgVerifiedBytes, (nEndPos-nStartPos)+1, aGuiltyClients.GetCount());
	if (aGuiltyClients.GetCount() > 0){
		// parse all recorded data for this file to produce a statistic for the involved clients
		
		// first init arrays for the statistic
		CArray<uint32, uint32> aDataCorrupt;
		CArray<uint32, uint32> aDataVerified;
		aDataCorrupt.SetSize(aGuiltyClients.GetCount());
		aDataVerified.SetSize(aGuiltyClients.GetCount());
		for (int j = 0; j < aGuiltyClients.GetCount(); j++)
			aDataCorrupt[j] = aDataVerified[j] = 0;

		// now the parsing
		for (int nPart = 0; nPart < m_aaRecords.GetCount(); nPart++){
			for (int i = 0; i < m_aaRecords[nPart].GetCount(); i++){
				for(int k = 0; k < aGuiltyClients.GetCount(); k++){
					if (m_aaRecords[nPart][i].m_dwIP == aGuiltyClients[k]){
						if (m_aaRecords[nPart][i].m_BBRStatus == BBR_CORRUPTED){
							// corrupted data records are always counted as at least blocksize or bigger
							aDataCorrupt[k] += max((m_aaRecords[nPart][i].m_nEndPos-m_aaRecords[nPart][i].m_nStartPos)+1, EMBLOCKSIZE);
						}
						else if(m_aaRecords[nPart][i].m_BBRStatus == BBR_VERIFIED){
							aDataVerified[k] += (m_aaRecords[nPart][i].m_nEndPos-m_aaRecords[nPart][i].m_nStartPos)+1;
						}
					}
				}
			}
		}
		for(int k = 0; k < aGuiltyClients.GetCount(); k++){
			// calculate the percentage of corrupted data for each client and ban
			// him if the limit is reached
			int nCorruptPercentage;
			if ((aDataVerified[k] + aDataCorrupt[k]) > 0)
				nCorruptPercentage = (int)(((uint64)aDataCorrupt[k]*100)/(aDataVerified[k] + aDataCorrupt[k]));
			else {
				AddDebugLogLine(DLP_HIGH, false, _T("CorruptionBlackBox: Programm Error: No records for guilty client found!"));
				ASSERT( false );
				nCorruptPercentage = 0;
			}
			if ( nCorruptPercentage > CBB_BANTHRESHOLD){

				CUpDownClient* pEvilClient = theApp.clientlist->FindClientByIP(aGuiltyClients[k]);
				if (pEvilClient != NULL){
					AddDebugLogLine(DLP_HIGH, false, _T("CorruptionBlackBox: Banning: Found client which send %s of %s corrupted data, %s"), CastItoXBytes(aDataCorrupt[k]), CastItoXBytes((aDataVerified[k] + aDataCorrupt[k])), pEvilClient->DbgGetClientInfo());
					theApp.clientlist->AddTrackClient(pEvilClient);
					pEvilClient->Ban(_T("Identified as sender of corrupt data"));
				}
				else{
					AddDebugLogLine(DLP_HIGH, false, _T("CorruptionBlackBox: Banning: Found client which send %s of %s corrupted data, %s"), CastItoXBytes(aDataCorrupt[k]), CastItoXBytes((aDataVerified[k] + aDataCorrupt[k])), ipstr(aGuiltyClients[k]));
					theApp.clientlist->AddBannedClient(aGuiltyClients[k]);
				}
			}
			else{
				CUpDownClient* pSuspectClient = theApp.clientlist->FindClientByIP(aGuiltyClients[k]);
				if (pSuspectClient != NULL){
					AddDebugLogLine(DLP_DEFAULT, false, _T("CorruptionBlackBox: Reporting: Found client which probably send %s of %s corrupted data, but it is within the acceptable limit, %s"), CastItoXBytes(aDataCorrupt[k]), CastItoXBytes((aDataVerified[k] + aDataCorrupt[k])), pSuspectClient->DbgGetClientInfo());
					theApp.clientlist->AddTrackClient(pSuspectClient);
				}
				else
					AddDebugLogLine(DLP_DEFAULT, false, _T("CorruptionBlackBox: Reporting: Found client which probably send %s of %s corrupted data, but it is within the acceptable limit, %s"), CastItoXBytes(aDataCorrupt[k]), CastItoXBytes((aDataVerified[k] + aDataCorrupt[k])), ipstr(aGuiltyClients[k]));
			}
		}
	}
}
Example #18
0
void CButtonCx::DrawString(CDC *drawDC, LPDRAWITEMSTRUCT lpDrawItemStruct)
{
	// テキストを得る。
	CString title;
	GetWindowText(title);

	// テキストが空の場合および GDI+ Font/Brush が設定されていない場合何もしない。
	if (title.IsEmpty() || m_GpFont == NULL || m_GpBrush == NULL)
	{
		return;
	}

	// 透過モードにする。
	drawDC->SetBkMode(TRANSPARENT);

	// テキストの描画位置
	CRect rect = (CRect) (lpDrawItemStruct->rcItem); // クライアント四角形の取得
	// マージン設定
	rect.top += m_Margin.top;
	rect.left += m_Margin.left;
	rect.bottom -= m_Margin.bottom;
	rect.right -= m_Margin.right;

	CArray<CString, CString> arr;
	arr.RemoveAll();

	CString resToken;
	int curPos = 0;
	resToken = title.Tokenize(L"\r\n", curPos);
	while (resToken != L"")
	{
		arr.Add(resToken);
		resToken = title.Tokenize(L"\r\n", curPos);
	}

	if (m_FontType == FT_GDI_PLUS || m_FontType == FT_AUTO)	// GDI+
	{
		Gdiplus::Graphics g(drawDC->m_hDC);

		const Gdiplus::PointF pointF(0.0, 0.0);
		Gdiplus::RectF extentF;

		for (int i = 0; i < arr.GetCount(); i++)
		{
			CRect r;
			r.top = (LONG) (((double) rect.Height()) / arr.GetCount() * i);
			r.bottom = (LONG) (((double) rect.Height()) / arr.GetCount() * (i + 1));
			r.left = rect.left;
			r.right = rect.right;

			g.MeasureString(arr.GetAt(i), arr.GetAt(i).GetLength() + 1, m_GpFont, pointF, &extentF); // "+ 1" for workdaround 

			REAL y;
			FontFamily ff;
			m_GpFont->GetFamily(&ff);
			REAL ascent = (REAL) ff.GetCellAscent(FontStyleRegular);
			REAL lineSpacing = (REAL) ff.GetLineSpacing(FontStyleRegular);

			y = r.CenterPoint().y - (extentF.Height * ascent / lineSpacing) / 2;

			Gdiplus::PointF pt(rect.CenterPoint().x - (extentF.Width / 2), y);
			Gdiplus::RectF rectF(pt.X, pt.Y, (REAL) extentF.Width, (REAL) extentF.Height);

			g.SetTextRenderingHint(TextRenderingHintAntiAlias);
			g.DrawString(arr.GetAt(i), -1, m_GpFont, rectF, m_GpStringformat, m_GpBrush);
		}
	}
	else // GDI
	{
		for (int i = 0; i < arr.GetCount(); i++)
		{
			CRect r;
			r.top = rect.top + (LONG) (((double) rect.Height()) / arr.GetCount() * i);
			r.bottom = rect.top + (LONG) (((double) rect.Height()) / arr.GetCount() * (i + 1));
			r.left = rect.left;
			r.right = rect.right;

			CRect rectI;
			CSize extent;
			HGDIOBJ oldFont = drawDC->SelectObject(m_Font);
			GetTextExtentPoint32(drawDC->m_hDC, arr.GetAt(i), arr.GetAt(i).GetLength() + 1, &extent);
			rectI.top = r.top + (r.Height() - extent.cy) / 2;
			rectI.bottom = rectI.top + extent.cy;
			rectI.left = r.left;
			rectI.right = r.right;
			DrawText(drawDC->m_hDC, arr.GetAt(i), arr.GetAt(i).GetLength(), r, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
			drawDC->SelectObject(oldFont);
		}
	}
	// いつか DirectWrite 描画に対応したいものである。。。
}
// -------------------------------------------------------------------------
// Detects activities in on step after all events are collected 
// -------------------------------------------------------------------------
int GroupingEventDetector::PostProcessActivities(CNewVisionDoc* doc) {
	CArray<INode*> node;
	CArray<IFuzzyCluster*> cluster;
	doc->m_ActivityData.sActivity.RemoveAll();
	SwarmActivity::last_id = 0;
	// TEMP: WRITE OUT ALL DISTANCES
	//System::IO::StreamWriter^ log = File::CreateText("F:\\My Documents\\My Research\\Results\\Data\\Activity Data\\distances.csv");
	//log->Write("ID, ");
	//for (POSITION posE = doc->m_ActivityData.sEvent.GetStartPosition(); posE != NULL;) {
	//	int id; SwarmEvent *ev;
	//	doc->m_ActivityData.sEvent.GetNextAssoc(posE, id, ev);
	//	if (m_EventEndBeforeFrame == -1 || ev->stop < m_EventEndBeforeFrame)
	//		log->Write(String::Format("{0}, ", id));
	//}
	//log->WriteLine();
	//for (POSITION posE = doc->m_ActivityData.sEvent.GetStartPosition(); posE != NULL;) {
	//	int id; SwarmEvent *ev;
	//	doc->m_ActivityData.sEvent.GetNextAssoc(posE, id, ev);
	//	if (m_EventEndBeforeFrame == -1 || ev->stop < m_EventEndBeforeFrame) {
	//		//log->Write(String::Format("{0}, ", id));
	//		for (POSITION posE2 = doc->m_ActivityData.sEvent.GetStartPosition(); posE2 != NULL;) {
	//			int id2; SwarmEvent *ev2;
	//			doc->m_ActivityData.sEvent.GetNextAssoc(posE2, id2, ev2);
	//			if (m_EventEndBeforeFrame == -1 || ev2->stop < m_EventEndBeforeFrame)
	//				log->Write(String::Format("{0:f4}, ", ev->DistanceSQR(ev2)));
	//		}
	//		log->WriteLine();
	//	}
	//}
	//log->Close();
	//return 0;
	//// ------------------- TEMP: TEST WITH 2D POINTS

	////// Uniform points
	////for (int i=0;i<100;i++) {
	////	node.Add(new Node2DPoint());
	////}

	//rnd_seed = cvRNG(1);
	//Cluster2DPoint::last_id = 0;
	//IFuzzyCluster::last_id = 0;
	//Node2DPoint::last_id = 0;
	//// Several clusters with noise
	//for (int c=0;c<8;c++) {
	//	double x1 = 20*cvRandReal(&rnd_seed), y1 = 20*cvRandReal(&rnd_seed);
	//	int N = (int)(10+0*cvRandReal(&rnd_seed));
	//	//int N = 10;
	//	for (int i=0;i<N;i++) {
	//		Node2DPoint *p1 = new Node2DPoint(x1+cvRandReal(&rnd_seed), y1+cvRandReal(&rnd_seed));
	//		p1->id = c*N+i;
	//		node.Add(p1);
	//	}
	//}

	//ClusteringMachine cm(param);
	//cm.RunFuzzy(node, cluster);

	//return 0;
	//// -------------------- END TEMP

	for (POSITION posE = doc->m_ActivityData.sEvent.GetStartPosition(); posE != NULL;) {
		int id; SwarmEvent *ev;
		doc->m_ActivityData.sEvent.GetNextAssoc(posE, id, ev);
		//TEMP
		//if (ev->id == 1 || ev->id == 2 || ev->id == 6 || ev->id == 7 || ev->id == 8)
		if (m_EventEndBeforeFrame == -1 || ev->stop < m_EventEndBeforeFrame)
			node.Add(ev);
	}

	ClusteringMachine cm(param);
	cm.RunFuzzy(node, cluster);

	// export to activity map
	for (int i=0;i<cluster.GetCount();i++) {
		((SwarmActivity*)(cluster[i]))->actors.RemoveAll();
		((SwarmActivity*)(cluster[i]))->start = INT_MAX;
		((SwarmActivity*)(cluster[i]))->stop = INT_MIN;
		for (POSITION pos = cluster[i]->rec.GetStartPosition(); pos != NULL;) {
			int nid; Record* r;
			cluster[i]->rec.GetNextAssoc(pos, nid, r);
			// for each significant event in the cluster
			if (r->u > m_minEventWeight) {
				// copy all actors from significant events
				for (POSITION posA = ((SwarmEvent*)r->node)->actors.GetStartPosition(); posA != NULL;) {
					int aid; double p;
					((SwarmEvent*)r->node)->actors.GetNextAssoc(posA, aid, p);
					p = 0;
					((SwarmActivity*)(cluster[i]))->actors.Lookup(aid, p);
					// accumulate weight from all events
					((SwarmActivity*)(cluster[i]))->actors.SetAt(aid, p+r->u*pow(r->psi,2));
					((SwarmActivity*)(cluster[i]))->events.SetAt(r->node->id, 1);
				}
			}
		}
		//// normalize actor weights
		//((SwarmActivity*)(cluster[i]))->Normalize();
		//// remove insignificant actors
		//((SwarmActivity*)(cluster[i]))->FilterActors(m_minActorWeight);
		//// normalize actor weights again
		//((SwarmActivity*)(cluster[i]))->Normalize();

		// populate swarming activity data
		if (((SwarmActivity*)(cluster[i]))->actors.GetCount()) {
			SwarmActivity *cl = (SwarmActivity*)cluster[i];
			//cl->p = cl->N;
			doc->m_ActivityData.sActivity.SetAt(cluster[i]->id, cl);
		}
	}

	return 0;
}
Example #20
0
BOOL CUPnpMgr::CleanedFillupBug()
{
	CSingleLock		localLock(&m_cs, TRUE);
	
	if (FAILED(m_nat.SearchDevice()))
		return FALSE;


	HRESULT		hr;
	USHORT		usIndex;
	USHORT		usExternalPort;
	CString		strProtocol;
	CString		strDesc;
	CString		strInternalClient;
	CString		strLocalIP;
	
	CArray<CUPnpNatMapping, const CUPnpNatMapping&>		arrMapping;
	CUPnpNatMapping										mapping;

	strLocalIP = GetLocalIPStr();

	for (usIndex = 0; usIndex < 128; usIndex++)		//	最多查询128项,以防止有些路由器可能会一直返回成功。
	{
		hr = m_nat.GetGenericPortMappingEntry(usIndex, NULL, &usExternalPort, &strProtocol,
												NULL, &strInternalClient, NULL, &strDesc);

		if (-1 != strDesc.Find(_T("eMule (")))			//	描述里包含指定字样
		{
			if (strInternalClient == strLocalIP)	//	是本机添加的映射
				m_nat.DeletePortMapping(CString(_T("")),usExternalPort, strProtocol);
			else
			{
				mapping.m_strInternalClient = strInternalClient;
				mapping.m_wExternalPort = usExternalPort;
				mapping.m_strProtocol = strProtocol;	
				arrMapping.Add(mapping);
			}
		}

		if (FAILED(hr))		//	返回Failed结果,表示已经全部取完了。
			break;
	}

	
	//	如果同一ip做的eMule映射超过3项,则很有可能是以前的bug所致。则清除。<begin>
	int			i;
	int			iMappingCount;
	CString		strTestIp;

	while (! arrMapping.IsEmpty())
	{
		strTestIp = arrMapping[0].m_strInternalClient;
		iMappingCount = 0;
		for (i = 0; i < arrMapping.GetCount(); i++)
		{
			if (strTestIp == arrMapping[i].m_strInternalClient)
				iMappingCount++;
		}

		for (i = arrMapping.GetCount() - 1; i >= 0; i--)
		{
			if (strTestIp == arrMapping[i].m_strInternalClient)
			{
				if (iMappingCount > 3)			
				{
					m_nat.DeletePortMapping(CString(_T("")),
											arrMapping[i].m_wExternalPort,
											arrMapping[i].m_strProtocol);
				}

				arrMapping.RemoveAt(i);
			}

		}
	}
	//	如果同一ip做的eMule映射超过3项,则很有可能是以前的bug所致。则清除。<end>


	return TRUE;


}