コード例 #1
0
ファイル: ManagerProperty.cpp プロジェクト: ShipuW/ebank-MFC
BOOL ManagerProperty::OnInitDialog()
{
	CDialogEx::OnInitDialog();
	//this->GetParent()->SendMessage(WM_CLOSE);//关闭父对话框
	CDatabase db;
	db.Open("bankmanagement");
	CString sqlstr,sqlstramount;
	sqlstr.Format(_T("select manager_name from manager where manager_login_name='%s'"), CurrentUser);
	CRecordset rs(&db);
	rs.Open(CRecordset::forwardOnly, (_T("%s"), sqlstr));
	CString	name;
	rs.GetFieldValue(_T("manager_name"), name);
	GetDlgItem(IDC_MANAGER_NAME)->SetWindowTextA((CString)name);
	rs.Close();
	////////////////////////////上姓名下金额
	sqlstramount.Format(_T("select money_amount from bank_account"));
	CRecordset rss(&db);
	rss.Open(CRecordset::forwardOnly, (_T("%f"), sqlstramount));
	CString	stramount;
	rss.GetFieldValue(_T("money_amount"), stramount);
	m_ManagerPropertyamount = _tstof(stramount);
	UpdateData(FALSE);
	rss.Close();
	db.Close();


	///////////////////////////////产生图表
	CSeries0 lineSeries = (CSeries0)m_chartfinal.Series(0);
	lineSeries.Clear();

	
	sqlstr.Format(_T("CREATE OR REPLACE VIEW `view_day_property`AS SELECT * FROM day_property ORDER BY day_property.dayproperty_id DESC LIMIT 10;"));
	
	db.Open("bankmanagement");
	db.ExecuteSQL(sqlstr);
	sqlstr.Format(_T("select day_time,bank_balance from view_day_property  ORDER BY dayproperty_id ASC;"));
	CRecordset rssss(&db);
	rssss.Open(CRecordset::forwardOnly, (_T("%s"), sqlstr));
	CString strx, strbalance;
	double daybalance;


	for (int i = 0; i<10; i++)
	{

		CString varDayTime;
		rssss.GetFieldValue(_T("day_time"), varDayTime);
		strx.Format(_T("%s"), varDayTime);

		CString varBankBalance;
		rssss.GetFieldValue(_T("bank_balance"), varBankBalance);
		strbalance.Format(_T("%s"), varBankBalance);
		daybalance = _ttof(strbalance);

		lineSeries.AddXY((double)i, daybalance, strx, 0);
		rssss.MoveNext();
	}

	rssss.Close();


	db.Close();


	return true;
}
コード例 #2
0
HRESULT CInArchive::Open2(IInStream *stream,
    const UInt64 *searchHeaderSizeLimit,
    CDatabase &database)
{
  database.Clear();
  RINOK(stream->Seek(0, STREAM_SEEK_SET, &database.StartPosition));

  RINOK(FindSignatureInStream(stream, NHeader::kMarker, NHeader::kMarkerSize,
      searchHeaderSizeLimit, database.StartPosition));

  RINOK(stream->Seek(database.StartPosition + NHeader::kMarkerSize, STREAM_SEEK_SET, NULL));
  if (!inBuffer.Create(1 << 17))
    return E_OUTOFMEMORY;
  inBuffer.SetStream(stream);
  inBuffer.Init();

  CInArchiveInfo &ai = database.ArchiveInfo;

  ai.Size = ReadUInt32();
  if (ReadUInt32() != 0)
    return S_FALSE;
  ai.FileHeadersOffset = ReadUInt32();
  if (ReadUInt32() != 0)
    return S_FALSE;

  ai.VersionMinor = ReadByte();
  ai.VersionMajor = ReadByte();
  ai.NumFolders = ReadUInt16();
  ai.NumFiles = ReadUInt16();
  ai.Flags = ReadUInt16();
  if (ai.Flags > 7)
    return S_FALSE;
  ai.SetID = ReadUInt16();
  ai.CabinetNumber = ReadUInt16();

  if (ai.ReserveBlockPresent())
  {
    ai.PerCabinetAreaSize = ReadUInt16();
    ai.PerFolderAreaSize = ReadByte();
    ai.PerDataBlockAreaSize = ReadByte();

    Skip(ai.PerCabinetAreaSize);
  }

  {
    if (ai.IsTherePrev())
      ReadOtherArchive(ai.PreviousArchive);
    if (ai.IsThereNext())
      ReadOtherArchive(ai.NextArchive);
  }
  
  int i;
  for (i = 0; i < ai.NumFolders; i++)
  {
    CFolder folder;

    folder.DataStart = ReadUInt32();
    folder.NumDataBlocks = ReadUInt16();
    folder.CompressionTypeMajor = ReadByte();
    folder.CompressionTypeMinor = ReadByte();

    Skip(ai.PerFolderAreaSize);
    database.Folders.Add(folder);
  }
  
  RINOK(stream->Seek(database.StartPosition + ai.FileHeadersOffset, STREAM_SEEK_SET, NULL));

  inBuffer.SetStream(stream);
  inBuffer.Init();
  for (i = 0; i < ai.NumFiles; i++)
  {
    CItem item;
    item.Size = ReadUInt32();
    item.Offset = ReadUInt32();
    item.FolderIndex = ReadUInt16();
    UInt16 pureDate = ReadUInt16();
    UInt16 pureTime = ReadUInt16();
    item.Time = ((UInt32(pureDate) << 16)) | pureTime;
    item.Attributes = ReadUInt16();
    item.Name = SafeReadName();
    int folderIndex = item.GetFolderIndex(database.Folders.Size());
    if (folderIndex >= database.Folders.Size())
      return S_FALSE;
    database.Items.Add(item);
  }
  return S_OK;
}
コード例 #3
0
ファイル: AccountDetail.cpp プロジェクト: ShipuW/ebank-MFC
BOOL AccountDetail::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	ModifyStyleEx(0, WS_EX_APPWINDOW);
	HICON m_hIcon;
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标
	
	AccountOperate.InsertColumn(1, _T("操作类型"), LVCFMT_LEFT, 200);
	AccountOperate.InsertColumn(2, _T("金额"), LVCFMT_LEFT, 80);
	AccountOperate.InsertColumn(3, _T("时间"), LVCFMT_LEFT, 80);
	
	
	CString sqlstr;
	sqlstr.Format(_T("select money_value,operate_time from operate_deposit where card_number ='%s'"), CardDetail);
	AccountOperate.DeleteAllItems();

	CDatabase db;
	db.Open("bankmanagement");
	CRecordset rs(&db);
	rs.Open(CRecordset::forwardOnly, (_T("%s"), sqlstr));
	while (!rs.IsEOF())
	{
		CString varOperateType;
		varOperateType = "存款";
		AccountOperate.InsertItem(0, varOperateType);
		CString varOperateAmount;
		rs.GetFieldValue(_T("money_value"), varOperateAmount);
		AccountOperate.SetItemText(0, 1, varOperateAmount);
		CString varOperateTime;
		rs.GetFieldValue(_T("operate_time"), varOperateTime);
		AccountOperate.SetItemText(0, 2, varOperateTime);
		rs.MoveNext();
	}
	rs.Close();
	AccountOperate.SetExtendedStyle(LVS_EX_FLATSB | LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES);
	//////////////////////////////////////////////////上面是list control内容,下面是编辑框内容
	
	
	CString sqlstrinfo;
	m_DetailCard = CardDetail;
	sqlstrinfo.Format(_T("select register_time,money_balance,card_type from card where card_number='%s'"),m_DetailCard);
	CRecordset rss(&db);
	rss.Open(CRecordset::forwardOnly, (_T("%s"), sqlstrinfo));
	
	while (!rss.IsEOF())
	{
		
		rss.GetFieldValue(_T("register_time"), m_DetailTime);
		
		rss.GetFieldValue(_T("money_balance"), m_DetailBalance);
		
		rss.GetFieldValue(_T("card_type"), m_DetailType);
		rss.MoveNext();
	}
	UpdateData(false);



	rss.Close();
	db.Close();
	return true;
}
コード例 #4
0
ファイル: SmartPlayList.cpp プロジェクト: mindcorrosive/xbmc
CStdString CSmartPlaylistRule::GetWhereClause(CDatabase &db, const CStdString& strType) const
{
  SEARCH_OPERATOR op = m_operator;
  if ((strType == "tvshows" || strType == "episodes") && m_field == FieldYear)
  { // special case for premiered which is a date rather than a year
    // TODO: SMARTPLAYLISTS do we really need this, or should we just make this field the premiered date and request a date?
    if (op == OPERATOR_EQUALS)
      op = OPERATOR_CONTAINS;
    else if (op == OPERATOR_DOES_NOT_EQUAL)
      op = OPERATOR_DOES_NOT_CONTAIN;
  }

  CStdString operatorString, negate;
  if (GetFieldType(m_field) == TEXTIN_FIELD)
  {
    if (op == OPERATOR_DOES_NOT_EQUAL)
      negate = " NOT";
  }
  else
  {
    // the comparison piece
    switch (op)
    {
    case OPERATOR_CONTAINS:
      operatorString = " LIKE '%%%s%%'"; break;
    case OPERATOR_DOES_NOT_CONTAIN:
      negate = " NOT"; operatorString = " LIKE '%%%s%%'"; break;
    case OPERATOR_EQUALS:
      operatorString = " LIKE '%s'"; break;
    case OPERATOR_DOES_NOT_EQUAL:
      negate = " NOT"; operatorString = " LIKE '%s'"; break;
    case OPERATOR_STARTS_WITH:
      operatorString = " LIKE '%s%%'"; break;
    case OPERATOR_ENDS_WITH:
      operatorString = " LIKE '%%%s'"; break;
    case OPERATOR_AFTER:
    case OPERATOR_GREATER_THAN:
    case OPERATOR_IN_THE_LAST:
      operatorString = " > '%s'"; break;
    case OPERATOR_BEFORE:
    case OPERATOR_LESS_THAN:
    case OPERATOR_NOT_IN_THE_LAST:
      operatorString = " < '%s'"; break;
    case OPERATOR_TRUE:
      operatorString = " = 1"; break;
    case OPERATOR_FALSE:
      negate = " NOT "; operatorString = " = 0"; break;
    default:
      break;
    }
  }

  // FieldInProgress does not have any values in m_parameter, it works on the operator
  if (m_field == FieldInProgress && (strType == "movies" || strType == "episodes"))
    return "idFile " + negate + " in (select idFile from bookmark where type = 1)";

  // now the query parameter
  CStdString wholeQuery;
  for (vector<CStdString>::const_iterator it = m_parameter.begin(); it != m_parameter.end(); /* it++ is done further down */)
  {
    CStdString parameter;
    if (GetFieldType(m_field) == TEXTIN_FIELD)
    {
      CStdStringArray split;
      StringUtils::SplitString(*it, ",", split);
      for (CStdStringArray::iterator itIn = split.begin(); itIn != split.end(); ++itIn)
      {
        if (!parameter.IsEmpty())
          parameter += ",";
        parameter += db.PrepareSQL("'%s'", (*itIn).Trim().c_str());
      }
      parameter = " IN (" + parameter + ")";
    }
    else
      parameter = db.PrepareSQL(operatorString.c_str(), it->c_str());

    if (GetFieldType(m_field) == DATE_FIELD)
    {
      if (m_operator == OPERATOR_IN_THE_LAST || m_operator == OPERATOR_NOT_IN_THE_LAST)
      { // translate time period
        CDateTime date=CDateTime::GetCurrentDateTime();
        CDateTimeSpan span;
        span.SetFromPeriod(*it);
        date-=span;
        parameter = db.PrepareSQL(operatorString.c_str(), date.GetAsDBDate().c_str());
      }
    }
    else if (m_field == FieldTime)
    { // translate time to seconds
      CStdString seconds; seconds.Format("%i", StringUtils::TimeStringToSeconds(*it));
      parameter = db.PrepareSQL(operatorString.c_str(), seconds.c_str());
    }

    CStdString query;
    CStdString table;
    if (strType == "songs")
    {
      table = "songview";

      if (m_field == FieldGenre)
        query = negate + " (" + GetField(FieldId, strType) + " IN (SELECT idSong FROM song_genre, genre WHERE song_genre.idGenre = genre.idGenre AND genre.strGenre" + parameter + ")";
      else if (m_field == FieldArtist)
        query = negate + " (" + GetField(FieldId, strType) + " IN (SELECT idSong FROM song_artist, artist WHERE song_artist.idArtist = artist.idArtist AND artist.strArtist" + parameter + ")";
      else if (m_field == FieldAlbumArtist)
        query = negate + " (" + table + ".idAlbum IN (SELECT idAlbum FROM album_artist, artist WHERE album_artist.idArtist = artist.idArtist AND artist.strArtist" + parameter + ")";
      else if (m_field == FieldLastPlayed && (m_operator == OPERATOR_LESS_THAN || m_operator == OPERATOR_BEFORE || m_operator == OPERATOR_NOT_IN_THE_LAST))
        query = "lastPlayed is NULL or lastPlayed" + parameter;
    }
    else if (strType == "albums")
    {
      table = "albumview";

      if (m_field == FieldGenre)
        query = negate + " (" + GetField(FieldId, strType) + " IN (SELECT song.idAlbum FROM song, song_genre, genre WHERE song.idSong = song_genre.idGenre AND song_genre.idGenre = genre.idGenre AND genre.strGenre" + parameter + ")";
      else if (m_field == FieldArtist)
        query = negate + " (" + GetField(FieldId, strType) + " IN (SELECT song.idAlbum FROM song, song_artist, artists WHERE song.idSong = song_artist.idSong AND song_artist.idArtist = artist.idArtist AND artist.strArtist" + parameter + ")";
      else if (m_field == FieldAlbumArtist)
        query = negate + " (" + GetField(FieldId, strType) + " IN (SELECT album_artist.idAlbum FROM album_artist, artist WHERE album_artist.idArtist = artist.idArtist AND artist.strArtist" + parameter + ")";
    }
    else if (strType == "movies")
    {
      table = "movieview";

      if (m_field == FieldGenre)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idMovie FROM genrelinkmovie JOIN genre ON genre.idGenre=genrelinkmovie.idGenre WHERE genre.strGenre" + parameter + ")";
      else if (m_field == FieldDirector)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idMovie FROM directorlinkmovie JOIN actors ON actors.idActor=directorlinkmovie.idDirector WHERE actors.strActor" + parameter + ")";
      else if (m_field == FieldActor)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idMovie FROM actorlinkmovie JOIN actors ON actors.idActor=actorlinkmovie.idActor WHERE actors.strActor" + parameter + ")";
      else if (m_field == FieldWriter)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idMovie FROM writerlinkmovie JOIN actors ON actors.idActor=writerlinkmovie.idWriter WHERE actors.strActor" + parameter + ")";
      else if (m_field == FieldStudio)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idMovie FROM studiolinkmovie JOIN studio ON studio.idStudio=studiolinkmovie.idStudio WHERE studio.strStudio" + parameter + ")";
      else if (m_field == FieldCountry)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idMovie FROM countrylinkmovie JOIN country ON country.idCountry=countrylinkmovie.idCountry WHERE country.strCountry" + parameter + ")";
      else if (m_field == FieldTrailer)
        query = negate + GetField(m_field, strType) + "!= ''";
      else if ((m_field == FieldLastPlayed || m_field == FieldDateAdded) && (m_operator == OPERATOR_LESS_THAN || m_operator == OPERATOR_BEFORE || m_operator == OPERATOR_NOT_IN_THE_LAST))
        query = GetField(m_field, strType) + " IS NULL OR " + GetField(m_field, strType) + parameter;
      else if (m_field == FieldInProgress)
        query = table + ".idFile " + negate + " IN (SELECT idFile FROM bookmark WHERE type = 1)";
      else if (m_field == FieldSet)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idMovie FROM setlinkmovie JOIN sets ON sets.idSet=setlinkmovie.idSet WHERE sets.strSet" + parameter + ")";
      else if (m_field == FieldTag)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idMedia FROM taglinks JOIN tag ON tag.idTag = taglinks.idTag WHERE tag.strTag" + parameter + " AND taglinks.media_type = 'movie')";
    }
    else if (strType == "musicvideos")
    {
      table = "musicvideoview";

      if (m_field == FieldGenre)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idMVideo FROM genrelinkmusicvideo JOIN genre ON genre.idGenre=genrelinkmusicvideo.idGenre WHERE genre.strGenre" + parameter + ")";
      else if (m_field == FieldArtist)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idMVideo FROM artistlinkmusicvideo JOIN actors ON actors.idActor=artistlinkmusicvideo.idArtist WHERE actors.strActor" + parameter + ")";
      else if (m_field == FieldStudio)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idMVideo FROM studiolinkmusicvideo JOIN studio ON studio.idStudio=studiolinkmusicvideo.idStudio WHERE studio.strStudio" + parameter + ")";
      else if (m_field == FieldDirector)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idMVideo FROM directorlinkmusicvideo JOIN actors ON actors.idActor=directorlinkmusicvideo.idDirector WHERE actors.strActor" + parameter + ")";
      else if ((m_field == FieldLastPlayed || m_field == FieldDateAdded) && (m_operator == OPERATOR_LESS_THAN || m_operator == OPERATOR_BEFORE || m_operator == OPERATOR_NOT_IN_THE_LAST))
        query = GetField(m_field, strType) + " IS NULL OR " + GetField(m_field, strType) + parameter;
    }
    else if (strType == "tvshows")
    {
      table = "tvshowview";

      if (m_field == FieldGenre)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idShow FROM genrelinktvshow JOIN genre ON genre.idGenre=genrelinktvshow.idGenre WHERE genre.strGenre" + parameter + ")";
      else if (m_field == FieldDirector)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idShow FROM directorlinktvshow JOIN actors ON actors.idActor=directorlinktvshow.idDirector WHERE actors.strActor" + parameter + ")";
      else if (m_field == FieldActor)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idShow FROM actorlinktvshow JOIN actors ON actors.idActor=actorlinktvshow.idActor WHERE actors.strActor" + parameter + ")";
      else if (m_field == FieldStudio)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idShow FROM tvshowview WHERE " + GetField(m_field, strType) + parameter + ")";
      else if (m_field == FieldMPAA)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idShow FROM tvshowview WHERE " + GetField(m_field, strType) + parameter + ")";
      else if (m_field == FieldDateAdded && (m_operator == OPERATOR_LESS_THAN || m_operator == OPERATOR_BEFORE || m_operator == OPERATOR_NOT_IN_THE_LAST))
        query = GetField(FieldDateAdded, strType) + " IS NULL OR " + GetField(FieldDateAdded, strType) + parameter;
    }
    else if (strType == "episodes")
    {
      table = "episodeview";

      if (m_field == FieldGenre)
        query = table + ".idShow" + negate + " IN (SELECT idShow FROM genrelinktvshow JOIN genre ON genre.idGenre=genrelinktvshow.idGenre WHERE genre.strGenre" + parameter + ")";
      else if (m_field == FieldDirector)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idEpisode FROM directorlinkepisode JOIN actors ON actors.idActor=directorlinkepisode.idDirector WHERE actors.strActor" + parameter + ")";
      else if (m_field == FieldActor)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idEpisode FROM actorlinkepisode JOIN actors ON actors.idActor=actorlinkepisode.idActor WHERE actors.strActor" + parameter + ")";
      else if (m_field == FieldWriter)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idEpisode FROM writerlinkepisode JOIN actors ON actors.idActor=writerlinkepisode.idWriter WHERE actors.strActor" + parameter + ")";
      else if ((m_field == FieldLastPlayed || m_field == FieldDateAdded) && (m_operator == OPERATOR_LESS_THAN || m_operator == OPERATOR_BEFORE || m_operator == OPERATOR_NOT_IN_THE_LAST))
        query = GetField(m_field, strType) + " IS NULL OR " + GetField(m_field, strType) + parameter;
      else if (m_field == FieldInProgress)
        query = table + ".idFile " + negate + " IN (SELECT idFile FROM bookmark WHERE type = 1)";
      else if (m_field == FieldStudio)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idEpisode FROM episodeview WHERE strStudio" + parameter + ")";
      else if (m_field == FieldMPAA)
        query = GetField(FieldId, strType) + negate + " IN (SELECT idEpisode FROM episodeview WHERE mpaa" + parameter + ")";
    }
    if (m_field == FieldVideoResolution)
      query = table + ".idFile" + negate + GetVideoResolutionQuery(*it);
    else if (m_field == FieldAudioChannels)
      query = table + ".idFile" + negate + " IN (SELECT DISTINCT idFile FROM streamdetails WHERE iAudioChannels " + parameter + ")";
    else if (m_field == FieldVideoCodec)
      query = table + ".idFile" + negate + " IN (SELECT DISTINCT idFile FROM streamdetails WHERE strVideoCodec " + parameter + ")";
    else if (m_field == FieldAudioCodec)
      query = table + ".idFile" + negate + " IN (SELECT DISTINCT idFile FROM streamdetails WHERE strAudioCodec " + parameter + ")";
    else if (m_field == FieldAudioLanguage)
      query = table + ".idFile" + negate + " IN (SELECT DISTINCT idFile FROM streamdetails WHERE strAudioLanguage " + parameter + ")";
    else if (m_field == FieldSubtitleLanguage)
      query = table + ".idFile" + negate + " IN (SELECT DISTINCT idFile FROM streamdetails WHERE strSubtitleLanguage " + parameter + ")";
    else if (m_field == FieldVideoAspectRatio)
      query = table + ".idFile" + negate + " IN (SELECT DISTINCT idFile FROM streamdetails WHERE fVideoAspect " + parameter + ")";
    if (m_field == FieldPlaycount && strType != "songs" && strType != "albums")
    { // playcount IS stored as NULL OR number IN video db
      if ((m_operator == OPERATOR_EQUALS && it->Equals("0")) ||
          (m_operator == OPERATOR_DOES_NOT_EQUAL && !it->Equals("0")) ||
          (m_operator == OPERATOR_LESS_THAN))
      {
        CStdString field = GetField(FieldPlaycount, strType);
        query = field + " IS NULL OR " + field + parameter;
      }
    }

    if (query.IsEmpty() && m_field != FieldNone)
      query = GetField(m_field,strType) + negate + parameter;
    
    it++;
    if (query.Equals(negate + parameter))
      query = "1";

    query = "(" + query + ")";
    if (it != m_parameter.end())
      query += " OR ";

    wholeQuery += query;
  }

  return wholeQuery;
}
コード例 #5
0
ファイル: TrainDlg.cpp プロジェクト: ywydigital/FaceDetection
void CTrainDlg::OnBnClickedTraining()
{
	// TODO: 在此添加控件通知处理程序代码
	CString exePath = "..\\haartraining\\Debug\\haartraining.exe";

	CString value;

	m_iSplits = 2;
	m_iStages = 4;

	value.Format("-data %s -vec %s -bg %s -npos %d -nneg %d -nsplits %d -nstages %d  -nonsym -mem 512 -w %d -h %d -mode all",
		m_data,m_vec,m_bg,m_iPositiveNum,m_iNegetiveNum,m_iSplits,m_iStages,m_iImgWidth,m_iImgHeight);
	ShellExecute((HWND)AfxGetMainWnd(),"open",exePath,value,NULL,SW_SHOW );
 
	CFileFind filefinder;
 
	CString SourcePath;
	//SourcePath.Format("E:\\训练分类器\\result.xml");
	SourcePath.Format("%s\\result.xml",m_data.Mid(0,m_positive.ReverseFind('\\')));
 
	CString filename;
 
	BOOL bfind = filefinder.FindFile(SourcePath);
 
	CString DisPath;
 
	if (bfind)
 
	{
 
	   bfind = filefinder.FindNextFile();
 
	   //filename = filefinder.GetFileName();
 
	   DisPath = "..\\classifier\\result.xml";
 
	   CopyFile(SourcePath,DisPath,1);

	    CDatabase db;

		 db.Open(NULL, FALSE, FALSE, _T("ODBC;DSN=face;UID=root;PWD=root"));
		 CString name, path, desc,str;
		 name = "result.xml";
		 path = "classifier\\\\result.xml";
		 desc = "训练分类器";

		 if(name == "" || path == "" || desc == "")
		 {
			 MessageBox("所有属性不能为空");
			 db.Close();
			 return;
		 }
	 
		 //判断该目录下分类器是否存在
		 CFileFind finder;
		 if( !finder.FindFile("..\\"+path))
		 {
			 MessageBox("该分类器不存在");
			 db.Close();
			 return;
		 }

		 str.Format("insert into classifier(cname,cpath,cdescribe)  values('%s','%s','%s')", name, path, desc);
		 db.ExecuteSQL(str);
		 db.Close();
		 MessageBox("添加成功");
 
	}
 
	filefinder.Close();

}
コード例 #6
0
UINT CNav_ExportCustomsDlg::ExportData(LPVOID p)
{
	
	HRESULT hRes;
	Excel::_ApplicationPtr appExcel;
	hRes = appExcel.CreateInstance( _T("Excel.Application"));

	CNav_ExportCustomsDlg *Dialog;
	Dialog = (CNav_ExportCustomsDlg*)p;

	if(Dialog != NULL)
	{
		

		CString sStart, sEnd;
		Dialog->m_EndDate.GetWindowText(sEnd);
		Dialog->m_StartDate.GetWindowText(sStart);

		CString sGTD;
		Dialog->m_EdGTDNUMBER.GetWindowText(sGTD);
		COleDateTime datStart,datEnd, cDate;
		datStart.ParseDateTime(sStart);
		datEnd.ParseDateTime(sEnd);
	
		CString sConnect;
		CString sServer, sDatabase;
		sServer = sReadFromIni(_T("DB"),_T("SERVER"),_T("svbyminssq3"));
		//sWriteToIni(_T("DB"),_T("SERVER"),sServer);
		sDatabase = sReadFromIni(_T("DB"),_T("DATABASE"),_T("SHATE-M-8"));
		//sWriteToIni(_T("DB"),_T("DATABASE"),sDatabase);


		
		Excel::WorkbooksPtr ExcelBooks;
		Excel::_WorkbookPtr ExcelBook;
		Excel::_WorksheetPtr ExcelSheet;
		Excel::RangePtr range;

		
		
		

		VARIANT bTRUE;
		bTRUE.vt = 11;
		bTRUE.boolVal = TRUE;
		appExcel->Visible[0] = FALSE;
		ExcelBook= appExcel->Workbooks->Add();
		ExcelSheet = ExcelBook->Worksheets->Item[1];

		sConnect.Format(_T("DRIVER=SQL Server;SERVER=%s;UID=;WSID=%s;Trusted_Connection=Yes;DATABASE=%s;LANGUAGE=русский"),sServer,GetWinUserName(),sDatabase);
		CDatabase* dBase;
		dBase = NULL;
		try
		{
			dBase = new(CDatabase);
			dBase->SetQueryTimeout(600);
			dBase->OpenEx(sConnect,CDatabase::noOdbcDialog);
			sConnect.Format(_T("EXEC [sp_setapprole] '%s', '%s', 'none', 0, 0"),_T("$ndo$shadow"),_T("FF5EC4E40F67BD4EDF3D04F8B84364DAD0")); 
			dBase->ExecuteSQL(sConnect);
		}
		catch(CDBException *exsept)
		{
			appExcel->Visible[0] = TRUE;
			Dialog->m_stState.SetWindowTextW(exsept->m_strError);
			exsept->Delete();
			if(dBase != NULL)
			{
				if(dBase->IsOpen())
				{
					dBase->Close();
				}
				delete(dBase);
			}
			dBase = NULL;
			Dialog->m_BtOK.ShowWindow(1);
			Dialog->SecondThread = NULL;
			return 0;
		}
		CString sSQL;
		try
		{
			

			CRecordset Query(dBase);
		
			int iField;
			CDBVariant dbValue;
			Dialog->m_stState.SetWindowTextW(_T("Формирование"));
			sGTD = sGTD + _T("'");
			sSQL = _T("select distinct SIH.[Posting Date],(SIL.[TTN Series]+SIL.[TTN Number]) AS TTN,SIL.[Item No_ 2], SIH.[Bill-to Name] ");
			sSQL = sSQL + _T(" from [")+sDatabase;
			sSQL = sSQL + _T("$Sales Invoice Header] as SIH join [");
			sSQL = sSQL + sDatabase;
			sSQL = sSQL + _T("$Sales Invoice Line] as SIL on SIL.[Document No_] = SIH.[No_] and SIL.[No_] is not null and SIL.[No_] <> ''  and SIL.[TTN Series] <> '' and SIL.[TTN Number] <> '' join [");
			sSQL = sSQL + sDatabase;
			sSQL = sSQL + _T("$Custom Declaration Relation] as CDR on CDR.[Item No_] = SIL.[No_] and CDR.[Document Type] = 5 and CDR.[CD No_] = '") + sGTD;
			sSQL = sSQL + _T(" where [Sales Process Type Code] = 'Б/Н_ДОСТАВКА' and Left(CONVERT ( nchar , SIH.[Posting Date], 112),8) >= '")+ datStart.Format(_T("%Y%m%d"))+_T("'");
			sSQL = sSQL + _T(" and Left(CONVERT ( nchar , SIH.[Posting Date], 112),8) <= '")+ datEnd.Format(_T("%Y%m%d"))+_T("'");
			//sSQL = sSQL + _T(" and CDR.[CD No_] = '") + sGTD;

			CString sDat;
			int iRow;
			iRow = 1;
			sDat = _T("Дата учета продажи");
			ExcelSheet->Cells->Item[iRow,2] = sDat.AllocSysString();
			sDat = _T("Номер ТТН, ТН");
			ExcelSheet->Cells->Item[iRow,3] = sDat.AllocSysString();
			sDat = _T("Код проданного товара (код товара2)");
			ExcelSheet->Cells->Item[iRow,4] = sDat.AllocSysString();
			sDat = _T("Клиент");
			ExcelSheet->Cells->Item[iRow,5] = sDat.AllocSysString();
	

			
			Query.Open(CRecordset::snapshot,sSQL, CRecordset::readOnly);
			while(!Query.IsEOF())
			{
				iRow++;
				
				if((iRow -2) % 100 == 0)
				{
					sSQL.Format(_T("Обработанно %d"),iRow-2);
					Dialog->m_stState.SetWindowTextW(sSQL);
				}
				iField = 0;
				Query.GetFieldValue(iField, dbValue);
				sDat = GetValue(&dbValue);
				ExcelSheet->Cells->Item[iRow,2] = sDat.AllocSysString();

				iField = 1;
				Query.GetFieldValue(iField, dbValue);
				sDat = GetValue(&dbValue);
				ExcelSheet->Cells->Item[iRow,3] = sDat.AllocSysString();

				iField = 2;
				Query.GetFieldValue(iField, dbValue);
				sDat = GetValue(&dbValue);
				ExcelSheet->Cells->Item[iRow,4] = sDat.AllocSysString();

				iField = 3;
				Query.GetFieldValue(iField, dbValue);
				sDat = GetValue(&dbValue);
				ExcelSheet->Cells->Item[iRow,5] = sDat.AllocSysString();

				Query.MoveNext();
			}
			Query.Close();

		}
		catch(CDBException *exsept)
		{
			/*appExcel->Visible[0] = TRUE;
			appExcel = NULL;*/
			appExcel->Visible[0] = TRUE;
			Dialog->m_stState.SetWindowTextW(exsept->m_strError);
			Dialog->m_EdError.SetWindowTextW(sSQL);
			
			exsept->Delete();
			if(dBase != NULL)
			{
				if(dBase->IsOpen())
				{
					dBase->Close();
				}
				delete(dBase);
			}
			Dialog->m_BtOK.ShowWindow(1);
			Dialog->SecondThread = NULL;
			dBase = NULL;

			return 0;
		}


		Dialog->m_stState.SetWindowTextW(_T("Выполненно"));
		Dialog->m_BtOK.ShowWindow(1);
	}
	appExcel->Visible[0] = TRUE;
	Dialog->SecondThread = NULL;
	return 1;
}
コード例 #7
0
ファイル: EdRptExport.cpp プロジェクト: zphseu/cuiyan
BOOL CEdRptExport::ExportDBData(ofstream &htm, ofstream &txt)
{
	CDatabase db;
	BOOL bRet = FALSE;

	CString csHeadFile = m_pDoc->m_szHeadRight;
	if (m_pDoc->m_szODBCLink.IsEmpty())
	{
		ShowMessage(m_pDoc->GetHWnd(), "没有给定数据库指针,也没有指定链接字!");
		return FALSE;
	}

	if (!db.OpenEx(m_pDoc->m_szODBCLink, CDatabase::openReadOnly | CDatabase::noOdbcDialog))
	{
		ShowMessage(m_pDoc->GetHWnd(), "无法打开数据库连接 %s", m_pDoc->m_szODBCLink);
		return FALSE;
	}

	try 
	{
		UINT nRecCount = m_pDoc->GetRecordCount(db);

		CString szSQL = m_pDoc->m_szSQL;
		if (nRecCount > (int)m_pDoc->m_nMaxRecordNum)
		{
			CString str;
			str.Format(_T("共有 %d 条记录,但模版设计最大记录数为 %d,\n是否只 %d 条记录?\n"
				"注意:如何选否,会给数据库很大压力,甚至取消操作!"), 
				nRecCount, m_pDoc->m_nMaxRecordNum, m_pDoc->m_nMaxRecordNum);
			
			UINT ulSelect = IDNO;
			if (m_pDoc->GetHWnd())
				ulSelect = MessageBox(m_pDoc->GetHWnd(), str, _T("EdFc"), MB_YESNOCANCEL);
			
			if (ulSelect == IDNO)
				;
			else if (ulSelect == IDCANCEL)
				return FALSE;
			else // IDYES
			{
				csHeadFile.Format(_T("  %d条记录未导出"), nRecCount - m_pDoc->m_nMaxRecordNum);
				nRecCount = m_pDoc->m_nMaxRecordNum;
				
				CString csDBDrv = getDBDriver(m_pDoc->m_szODBCLink);
				csDBDrv.MakeLower();
				if (csDBDrv.Find("oracle") >= 0)
				{
					CString szTmp = szSQL;
					szTmp.MakeLower();
					int nFind = szTmp.Find(" where ");
					if (nFind > 0)
					{
						szTmp.Format(" ROWNUM <= %d AND ", m_pDoc->m_nMaxRecordNum);
						szSQL.Insert(nFind + (int)_tcslen(" where "), (LPCSTR)szTmp);
					}
					else
					{
						szTmp.Format(" WHERE ROWNUM <= %d ", m_pDoc->m_nMaxRecordNum);
						szSQL += szTmp;
					}
				}
				else if (csDBDrv.Find("mysql") >= 0)
				{
					CString szTmp;
					szTmp.Format(" Limit 0, %d ", m_pDoc->m_nMaxRecordNum);
					szSQL += szTmp;
				}
// 				else if (csDBDrv.IsEmpty())
// 					ShowMessage(m_pDoc->GetHWnd(), "报表打印组件无法判断该数据库的类型。");
				else
				{
					CString str;
					str.Format(_T("[ %s ] 数据库无法使用修改SQL的方法限制记录个数,而打开大数据集可能会出现异常\n,是否先修改查询条件,再进行打印?"), csDBDrv);
					if (m_pDoc->GetHWnd() && MessageBox(m_pDoc->GetHWnd(), str,_T("BSRpter"), MB_YESNO) == IDYES)
						return FALSE;
				}
			}
		}
		
		CRecordset rc(&db);
		rc.Open(CRecordset::forwardOnly, szSQL);
		UINT nFieldCount = rc.GetODBCFieldCount();
		
		CString szTitle = m_pDoc->m_szTitle;
		TxtToHtml(szTitle);

		CString szHeadRight = m_pDoc->m_szHeadRight;
		TxtToHtml(szHeadRight);
		htm << "<html><head><title>" 
			<< (LPCTSTR)szTitle 
			<< "</title></head>"
			<< endl;

		htm << "<body>" << endl
			<< "<table width=100%>" << endl
			<< "<tr>" << endl
			<< "\t<td width=20%>&nbsp;</td>" << endl
			<< "\t<td width=60% align=center><font size=+3>" 
			<< (LPCTSTR)szTitle
			<< "</font></td>" << endl
			<< "\t<td width=20% align=right>"
			<< (LPCTSTR)csHeadFile
			<< "</td>" << endl 
			<< "</tr>" << endl
			<< "</table>" << endl;

		htm << "<table border=1 width=100%>" << endl
			<< "<tr>" << endl;

		
		int nWidth = 0;
		for (UINT col = 0; col < nFieldCount; col++)
			nWidth += m_pDoc->m_ColFmt[col].width;

		CString str;
		for (col = 0; col < nFieldCount; col++)
		{	
			str = m_pDoc->m_ColFmt[col].name;

			if (str.IsEmpty())
			{
				CODBCFieldInfo fi;
				rc.GetODBCFieldInfo(col, fi);
				str = fi.m_strName;
			}

			txt << "\"" << (LPCTSTR)str << "\"";
			TxtToHtml(str);
			htm << "\t<td  width=" << m_pDoc->m_ColFmt[col].width * 100 / nWidth
				<< "%  align=center>" << (LPCTSTR)str << "</td>" << endl;
			
			if (col == nFieldCount - 1)
			{
				txt << endl;
				htm << "</tr>" << endl;
			}
			else
				txt << ',';
		}
		
		if (m_pDoc->GetHWnd())
			::SendMessage(m_pDoc->GetHWnd(), WM_CREATEPROGRESS, nRecCount, 0);

		CDBVariant varValue;
		CString strHtml;
		UINT nCount = 0;
		for(UINT row = 0; row < nRecCount; row ++)
		{
			htm << "<tr>" << endl;

			for (UINT col = 0; col < nFieldCount; col ++)
			{
				strHtml = _T("");
				rc.GetFieldValue(col, varValue);

				if (varValue.m_dwType == DBVT_BINARY)
				{
					str = GetPicFile(varValue.m_pbinary, nCount++);
					
					if (str.IsEmpty())	//error
						continue;
					
					m_ZipArc.AddFileToZip(str);
					DeleteFile(str);
					str = str.Right(str.GetLength() - str.ReverseFind('\\') - 1);
					strHtml.Format("<A href=%s>%s</A>", str, str);
				}
				else 
					str = m_pDoc->GetVarStr(&varValue, m_pDoc->m_ColFmt[col].format);

				varValue.Clear();
				
				txt << "\"" << (LPCTSTR)str << "\"";
				
				TxtToHtml(str);
				if (strHtml.IsEmpty())
					strHtml = str;
					
				htm << "\t<td align=center>" << (LPCTSTR)strHtml << "</td>" << endl;
				
				if (col == nFieldCount - 1)
				{
					txt << endl;
					htm << "</tr>" << endl;
				}
				else
					txt << ',';
			}

			if (m_pDoc->GetHWnd())
				::SendMessage(m_pDoc->GetHWnd(), WM_STEPPROGRESS, nRecCount, row);

			rc.MoveNext();
		}
		
		rc.Close();
	
		CString szFootLeft = m_pDoc->m_szFootLeft;
		TxtToHtml(szFootLeft);
		CString szFootRight = m_pDoc->m_szFootRight;
		if (szFootRight.IsEmpty())
			szFootRight = CTime::GetCurrentTime().Format("%m/%d/%y %H:%M:%S");
		TxtToHtml(szFootRight);

		htm << "</table>" << endl
			<< "<p>" << endl
			<< "<table width=100%>" << endl
			<< "<tr>" << endl 
			<< "\t<td width=50% align=left>"
			<< (LPCTSTR)szFootLeft
			<< "</td>" << endl
			<< "\t<td width=50% align=right>"
			<< (LPCTSTR)szFootRight
			<< "</td>" << endl
			<< "</table>" << endl
			
			<< "<p><hr>" << endl
			<< "<b>FmtFile Infomation</b><br>" << endl
			<< "<ul>" << endl
			<< "\t<li>ODBC: " << (LPCTSTR)m_pDoc->m_szODBCLink << "<br>" << endl
			<< "\t<li>SQL : " << (LPCTSTR)m_pDoc->m_szSQL
			<< "</ul>" << endl
			<< "</body>" << endl
			<< "</html>" << endl;
		
		if (m_pDoc->GetHWnd())
			::SendMessage(m_pDoc->GetHWnd(), WM_DESTROYPROGRESS, 0, 0);
		
		bRet = TRUE;
	}
	catch(CException *edb)
	{
		static TCHAR lpszError[MAX_PATH];
		CString csError;

		if (edb->GetErrorMessage(lpszError, MAX_PATH))
			csError = lpszError;

		if (csError.GetLength() <= 0)
			csError = _T("无法获得数据!");
		
		ShowMessage(m_pDoc->GetHWnd(), csError);

		edb->Delete();
		bRet = FALSE;
	}
	catch(...)
	{
		ShowMessage(m_pDoc->GetHWnd(), _T("无法获得数据!"));
		bRet = FALSE;
	}

	db.Close();

	return bRet;
}
コード例 #8
0
ファイル: LDlg1.cpp プロジェクト: akreddysoft/CollegeCode
BOOL CLDlg::OnInitDialog()
{
	CDialog::OnInitDialog();
	 m_hYellowBrush=(HBRUSH)GetStockObject(BLACK_BRUSH);

	 m_hRedBrush=(HBRUSH)GetStockObject(BLACK_BRUSH);


	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	
	
///////////////////////// initializations ///////////////////////////////////

pt1[0].x=0;
pt1[0].y=0;
pt2[0].x=1;
pt2[0].y=1; 
pt1[1].x=0;
pt1[1].y=3;
pt2[1].x=0;
pt2[1].y=3; 
pt1[2].x=8;
pt1[2].y=7;
pt2[2].x=9;
pt2[2].y=9; 
pt1[3].x=8;
pt1[3].y=5;
pt2[3].x=9;
pt2[3].y=6; 
pt1[4].x=4;
pt1[4].y=4;
pt2[4].x=5;
pt2[4].y=5; 

cmpt[0].x=0;
cmpt[0].y=0;
cmpt[1].x=0;
cmpt[1].y=4;
cmpt[2].x=5;
cmpt[2].y=5;
cmpt[3].x=5;
cmpt[3].y=7;
cmpt[4].x=8;
cmpt[4].y=8;

///////////////////////// initializations ///////////////////////////////////



///////////////////////////////database read from floortab/////////////////////////////////////////////
    CDatabase xx;

	xx.Open("ODBC;DSN=geoinfo");
	CRecordset dbSQL(&xx);
	dbSQL.Open(CRecordset::forwardOnly,"select * from floortab");
	cnt=0;
	while(!dbSQL.IsEOF()) 
	{
	CString xy;
	dbSQL.GetFieldValue("fid",xy);
	flid[cnt]=atoi(xy);
	dbSQL.GetFieldValue("frows",xy);
	flrows[cnt]=atoi(xy);
	dbSQL.GetFieldValue("fclmns",xy);
	flclmns[cnt++]=atoi(xy);
	dbSQL.MoveNext();	
	}

///////////////////////////////database read from floortab//////////////////////////////////////////////

///////////////////////////////database read from labtab//////////////////////////////////////////////
	CRecordset dblab(&xx);
	dblab.Open(CRecordset::forwardOnly,"select * from labtab");
	labcount=0;
	while(!dblab.IsEOF()) 
	{
	CString xy;
	dblab.GetFieldValue("labid",xy);
	labid[labcount]=atoi(xy);

	dblab.GetFieldValue("fid",xy);
	labfl[labcount]=atoi(xy);
	
	dblab.GetFieldValue("labname",xy);
	strcpy(labname[labcount],xy);
	
	dblab.GetFieldValue("labrow1",xy);
	pt1[labcount].x=atoi(xy);
	
	dblab.GetFieldValue("labclmn1",xy);
	pt1[labcount].y=atoi(xy);
	
	dblab.GetFieldValue("labrow2",xy);
	pt2[labcount].x=atoi(xy);
	
	dblab.GetFieldValue("labclmn2",xy);
	pt2[labcount].y=atoi(xy);

	dblab.GetFieldValue("labrows",xy);
	labrows[labcount]=atoi(xy);

	dblab.GetFieldValue("labclmns",xy);
	labclmns[labcount++]=atoi(xy);

	
	dblab.MoveNext();	
	}
	
///////////////////////////////database read from labtab//////////////////////////////////////////////
	
///////////////////////////////database read from labtab//////////////////////////////////////////////
	CRecordset dbcmp(&xx);
	dbcmp.Open(CRecordset::forwardOnly,"select * from comptab");
	cmcount=0;
	while(!dbcmp.IsEOF()) 
	{
	CString xy;
	dbcmp.GetFieldValue("cmid",xy);
	cmid[cmcount]=atoi(xy);
	dbcmp.GetFieldValue("labid",xy);
	cmlabid[cmcount]=atoi(xy);
	dbcmp.GetFieldValue("ptx",xy);
	cmpt[cmcount].x =atoi(xy);
	dbcmp.GetFieldValue("pty",xy);
	cmpt[cmcount].y =atoi(xy);

	dbcmp.GetFieldValue("cmip1",xy);
	cmip[cmcount][0] =atoi(xy);

	dbcmp.GetFieldValue("cmip2",xy);
	cmip[cmcount][1] =atoi(xy);

	dbcmp.GetFieldValue("cmip3",xy);
	cmip[cmcount][2] =atoi(xy);

	dbcmp.GetFieldValue("cmip4",xy);
	cmip[cmcount][3] =atoi(xy);

	cmcount++;
	dbcmp.MoveNext();	
	}
	
	
///////////////////////////////database read from labtab//////////////////////////////////////////////
return TRUE;  // return TRUE  unless you set the focus to a control
}
コード例 #9
0
ファイル: EdRptDoc.cpp プロジェクト: zphseu/cuiyan
BOOL CEdRptDoc::GetDataFromDB()
{
	CDatabase db;
	BOOL bRet = FALSE;
	try 
	{
		if (m_szODBCLink.IsEmpty())
		{
			ShowMessage(m_hWnd, "没有给定数据库指针,也没有指定链接字!");
			return FALSE;
		}

		if (!db.OpenEx(m_szODBCLink, CDatabase::openReadOnly | CDatabase::noOdbcDialog))
		{
			ShowMessage(m_hWnd, "无法打开数据库连接 %s", m_szODBCLink);
			return FALSE;
		}

		m_nRecCount = GetRecordCount(db);
		CRecordset rc(&db);
		
		CString szSQL = m_szSQL;
		CString csHeadRight = m_szHeadRight;
		if (m_nRecCount > (int)m_nMaxRecordNum)
		{
			CString str;
			str.Format(_T("共有 %d 条记录,但模版设计最大记录数为 %d,\n是否只 %d 条记录?\n"
				"注意:如何选否,会给数据库很大压力,甚至取消操作!"), 
				m_nRecCount, m_nMaxRecordNum, m_nMaxRecordNum);
			
			UINT ulSelect = IDNO;
			if (m_hWnd)
				ulSelect = MessageBox(m_hWnd, str, _T("BSRpter"), MB_YESNOCANCEL);

			if (ulSelect == IDNO)
				;
			else if (ulSelect == IDCANCEL)
				return FALSE;
			else // IDYES
			{
				csHeadRight.Format(_T("  %d条记录未打印"), m_nRecCount - m_nMaxRecordNum);
				m_nRecCount = m_nMaxRecordNum;
				
				CString csDBDrv = getDBDriver(m_szODBCLink);
				csDBDrv.MakeLower();
				if (csDBDrv.Find("oracle") >= 0)
				{
					CString szTmp = szSQL;
					szTmp.MakeLower();
					int nFind = szTmp.Find(" where ");
					if (nFind > 0)
					{
						szTmp.Format("ROWNUM <= %d AND ", m_nMaxRecordNum);
						szSQL.Insert(nFind + (int)_tcslen(" where "), (LPCSTR)szTmp);
					}
					else
					{
						szTmp.Format(" WHERE ROWNUM <= %d ", m_nMaxRecordNum);
						szSQL += szTmp;
					}
				}
				else if (csDBDrv.Find("mysql") >= 0)
				{
					CString szTmp;
					szTmp.Format(" Limit 0, %d ", m_nMaxRecordNum);
					szSQL += szTmp;
				}
				else
				{
					CString str;
					str.Format(_T("[ %s ] 数据库无法使用修改SQL的方法限制记录个数,"
						"而打开大数据集可能会出现异常\n,是否先修改查询条件,再进行打印?")
						, csDBDrv);
					if (m_hWnd != NULL && MessageBox(m_hWnd, str,_T("EdFc"), MB_YESNO) == IDYES)
						return FALSE;
				}
			}
		}

		rc.Open(CRecordset::forwardOnly, szSQL);
		m_nFieldCount = rc.GetODBCFieldCount();
		
		while (m_ColFmt.GetSize() > m_nFieldCount && m_nFieldCount > 1)
			m_ColFmt.RemoveAt(m_ColFmt.GetSize() - 1);
		
		COLFMT cf;
		while (m_ColFmt.GetSize() < m_nFieldCount)
			m_ColFmt.Add(cf);
				
		m_Grid.DeleteAllItems();
		int nRowCount = m_nRecCount + (m_bFootSum ? 2 : 1);
		m_Grid.SetRowCount(nRowCount);
		m_Grid.SetColumnCount(m_nFieldCount);
		
		// set ColumName;
		GV_ITEM Item;
		Item.mask = GVIF_TEXT|GVIF_FORMAT;	
		Item.row = 0;
		Item.nFormat = DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS|DT_NOPREFIX;
		for (Item.col = 0; Item.col < m_nFieldCount; Item.col++)
		{	
			m_Grid.SetColumnWidth(Item.col, m_ColFmt[Item.col].width);
			Item.szText = m_ColFmt[Item.col].name;			

			if (m_ColFmt[Item.col].name.IsEmpty())
			{
				CODBCFieldInfo fi;
				rc.GetODBCFieldInfo(Item.col, fi);
				Item.szText = fi.m_strName;
			}

			m_Grid.SetItem(&Item);
		}

		if (m_hWnd != NULL && m_nRecCount > 0)
			::SendMessage(m_hWnd, WM_CREATEPROGRESS, m_nRecCount, 0);

		CDBVariant varValue;
		Item.mask = GVIF_TEXT|GVIF_FORMAT;
		Item.nFormat = DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS|DT_NOPREFIX;
		for(int row = 0; row < m_nRecCount; row ++)
		{
			for (int col = 0; col < m_nFieldCount; col ++)
			{
				rc.GetFieldValue(col, varValue);
				Item.row = row + 1;
				Item.col = col;
				Item.szText = GetVarStr(&varValue, m_ColFmt[col].format);
				m_Grid.SetItem(&Item);	
				varValue.Clear();
			}
			
			if (m_hWnd != NULL)
				::SendMessage(m_hWnd, WM_STEPPROGRESS, m_nRecCount, row);
			
			rc.MoveNext();
		}
		
		if (m_bFootSum)
			GetStaticData(rc);
		
		rc.Close();	
		

		if (m_hWnd != NULL)
			::SendMessage(m_hWnd, WM_DESTROYPROGRESS, 0, 0);

		bRet = TRUE;
	}
	catch(CException *edb)
	{
		static TCHAR lpszError[MAX_PATH];
		CString csError;

		if (edb->GetErrorMessage(lpszError, MAX_PATH))
			csError = lpszError;

		if (csError.GetLength() <= 0)
			csError = _T("无法获得数据!");
		
		ShowMessage(m_hWnd, csError);

		edb->Delete();
	}
	catch(...)
	{
		ShowMessage(m_hWnd, _T("无法获得数据!"));
	}

	return bRet;
}
コード例 #10
0
ファイル: UGODBC.CPP プロジェクト: redame/Trading
/***************************************************
CUGODBCDatasource::Browse : call this function to invoke the
ODBC driver to prompt for connection params.

    This function gathers information about all of the  
    tables in the datasource selected, storing the information
    in the array m_dsInfoArray for later retrieval.  

    This function also saves the resulting connect string for
    later use.  

****************************************************/
int CUGODBCDatasource::Browse(HWND hwnd){


	HENV henv;
	HDBC hdbc;
	HSTMT hstmt;
	RETCODE retcode;
	SQLTCHAR  buf[255];

	SQLTCHAR  sqlerror[255];
	SQLTCHAR  sqlstate[255];
	SDWORD nerr, cbVal;
	SWORD num;

	// for table info....
	SQLTCHAR	szTableQualifier[128];
	SQLTCHAR	szTableOwner[128];
	SQLTCHAR	szTableName[128];
	SQLTCHAR	szTableType[128];
	SQLTCHAR	szRemarks[255];

	// close open db
	Close();
	
	// clean up previous data
	m_connectString = "";

	m_tableCount = 0;


	
	retcode = SQLAllocEnv(&henv);              // Environment handle 

	if (retcode == SQL_ERROR) {
		AfxMessageBox(_T("Probable memory allocation error in SQLAllocEnv"));
		return (int) retcode;
	}


	retcode = SQLAllocConnect(henv,&hdbc);

	if (retcode == SQL_ERROR) {
		ReportSQLError(henv, SQL_NULL_HDBC, SQL_NULL_HSTMT, retcode, _T("SQLAllocConnect"));
		SQLFreeEnv(henv);
		return (int) retcode;
	}		

	if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) {

		// Set login timeout to 5 seconds. 
		 SQLSetConnectOption(hdbc, SQL_LOGIN_TIMEOUT, 5);
		// Connect to data source 
        // this should cause the ODBC Driver to come up with the
		// necessary prompts to form a connect string...
		retcode = SQLDriverConnect(hdbc,hwnd,(SQLTCHAR*)_T(""),
							0,buf,254,&num,SQL_DRIVER_PROMPT);

							
		if (retcode != SQL_SUCCESS) {
			#ifdef UG_REPORT_ERROR
				ReportSQLError(henv, hdbc, SQL_NULL_HSTMT, retcode, _T("SQLDriverConnect"));
			#endif
			// user probably cancelled connection...
                if (retcode != SQL_SUCCESS_WITH_INFO) {
    			SQLFreeConnect(hdbc);
    			SQLFreeEnv(henv);
				return retcode;
                }
		}

			

		if(retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO){
			// retcode from SQLDriverConnect...
			// should be cool to try to open a recordset with the info 
			// we have here in buf...
			CDatabase db;
			TCHAR buf2[255];
			UGStr::stprintf(buf2,255,_T("ODBC;%s"),buf);

            // now we have the connect string in buf2 - but wait to
            // see if we can actually open the db before storing 
            // it in m_connectString...

			try {
				retcode = db.Open(NULL,FALSE,FALSE,buf2);
			}		
			catch(CMemoryException* e){
				#ifdef UG_ODBC_REPORTERROR
					e->ReportError();
				#endif
				e->Delete();
				AfxAbort();
			}
			catch(CDBException* e){
				// standard procedure for ODBC - save the 
				// RETCODE code for the return value - 
				// Report on the error - optional -
				// use Delete to delete the exception object
				RETCODE er = e->m_nRetCode;
				#ifdef UG_ODBC_REPORTERROR
					e->ReportError();
				#endif
				e->Delete();
    			SQLFreeConnect(hdbc);
    			SQLFreeEnv(henv);
				return (int)er;
			}

			// now, given an open connection, we should
			// be able to set up a statement handle..
			retcode = SQLAllocStmt(hdbc, &hstmt);

			
			switch (retcode) {
				case SQL_SUCCESS: {
				//	AfxMessageBox("SQLAllocStmt returned success ");
				//	AfxMessageBox((LPCSTR)buf);
					break;
				}
				case SQL_SUCCESS_WITH_INFO:{
					AfxMessageBox(_T("SQLAllocStmt returned success with info"));
					// this indicates that there is a driver specific warning
					// to be investigated...
					SQLError(SQL_NULL_HENV,hdbc,SQL_NULL_HSTMT,sqlstate,
											&nerr,sqlerror,254,&num);
					AfxMessageBox((LPCTSTR)sqlstate);
					AfxMessageBox((LPCTSTR)sqlerror);
					break;
				}
				case SQL_NO_DATA_FOUND:{
					AfxMessageBox(_T("SQLAllocStmt returned no data found"));
					break;
				}
				case SQL_ERROR:{
					AfxMessageBox(_T("SQLAllocStmt returned sql error"));
					SQLError(SQL_NULL_HENV,hdbc,SQL_NULL_HSTMT,sqlstate,&nerr,sqlerror,254,&num);
					AfxMessageBox((LPCTSTR)sqlstate);
					AfxMessageBox((LPCTSTR)sqlerror);
					break;
				}
				case SQL_INVALID_HANDLE:{
					AfxMessageBox(_T("SQLDriverConnect returned invalid handle"));
					break;
				}
				default:
					break;
				}

				// ok - now lets see if we can enumerate the tables
				// contained in the database...

				retcode = SQLTables(hstmt,	// statement handle for
												// retrieved results
						  NULL,					// szTableQualifier
						  SQL_NTS,				// cbTableQualifier
						  NULL,					// szTableOwner
						  SQL_NTS,				// cbTableOwner
						  NULL,					// szTableName
						  SQL_NTS,				// cbTableName
						  (SQLTCHAR*)_T("'TABLE','VIEW',\
						  'SYSTEM TABLE','GLOBAL TEMPORARY','LOCAL TEMPORARY',\
						  'ALIAS','SYNONYM'"),			// szTableType (list of
												// table types to match)
						  SQL_NTS);					// cbTableTypes
				
                if (retcode == SQL_ERROR || retcode == SQL_SUCCESS_WITH_INFO) {
					ReportSQLError(henv, hdbc, hstmt, retcode, _T("SQLTables"));
        			SQLFreeStmt(hstmt, SQL_DROP);
		        	SQLDisconnect(hdbc);
        			SQLFreeConnect(hdbc);
			        SQLFreeEnv(henv);
                    return retcode;         // unable to query tables 
                                            // User should see message box
                }


                // now - can we iterate through the tables found?
#ifndef _UNICODE
				SQLBindCol(hstmt, 1, SQL_C_CHAR, szTableQualifier, 128, &cbVal);
				SQLBindCol(hstmt, 2, SQL_C_CHAR, szTableOwner, 128, &cbVal);
				SQLBindCol(hstmt, 3, SQL_C_CHAR, szTableName, 128, &cbVal);
				SQLBindCol(hstmt, 4, SQL_C_CHAR, szTableType, 128, &cbVal);
				SQLBindCol(hstmt, 5, SQL_C_CHAR, szRemarks, 255, &cbVal);
#else
				SQLBindCol(hstmt, 1, SQL_UNICODE_CHAR, szTableQualifier, 128, &cbVal);
				SQLBindCol(hstmt, 2, SQL_UNICODE_CHAR, szTableOwner, 128, &cbVal);
				SQLBindCol(hstmt, 3, SQL_UNICODE_CHAR, szTableName, 128, &cbVal);
				SQLBindCol(hstmt, 4, SQL_UNICODE_CHAR, szTableType, 128, &cbVal);
				SQLBindCol(hstmt, 5, SQL_UNICODE_CHAR, szRemarks, 255, &cbVal);
#endif
				retcode = SQLFetch(hstmt);

				if (retcode == SQL_ERROR || retcode == SQL_SUCCESS_WITH_INFO)
					ReportSQLError(henv, hdbc, hstmt, retcode, _T("SQLFetch"));

				if (retcode != SQL_NO_DATA_FOUND)
					m_connectString = (LPTSTR)buf2;	// save connection string!


                // Subsequent calls to GetTableInfo will be able to 
                // retrieve this information...
				while (retcode != SQL_NO_DATA_FOUND) {
					UGStr::tcscpy((LPTSTR)m_dsInfoArray[m_tableCount].tableQualifier,128,(LPTSTR)szTableQualifier);
					UGStr::tcscpy((LPTSTR)m_dsInfoArray[m_tableCount].tableOwner,128, (LPTSTR)szTableOwner);
					UGStr::tcscpy((LPTSTR)m_dsInfoArray[m_tableCount].tableName,128,(LPTSTR)szTableName);
					UGStr::tcscpy((LPTSTR)m_dsInfoArray[m_tableCount].tableType,128,(LPTSTR)szTableType);
					UGStr::tcscpy((LPTSTR)m_dsInfoArray[m_tableCount].remarks,255,(LPTSTR)szRemarks);
					
					m_tableCount++;
					if (m_tableCount >= MAX_TABLES)
						break;
					retcode = SQLFetch(hstmt);

				}
			}
コード例 #11
0
/*
 * Adapt database to new description
 * \param description is the latest xml description of the database
 * \returns true is adaptation succeded
 */
CDatabase*	CDatabase::adapt(const string& description)
{
	PDS_DEBUG("adapt()");

	if (!initialised())
	{
		PDS_WARNING("adapt(): failed, database not initialised");
		return NULL;
	}

	// get 'From' HashKey
	CHashKey	hash1 = _Description.getHashKey();
	// get 'Into' HashKey
	CHashKey	hash2 = getSHA1((const uint8*)(description.c_str()), (uint32)description.size());

	// same hash, ok go on
	if (hash1 == hash2)
		return this;

	// build a clean reference if needed
	if (!isReferenceUpToDate())
	{
		if (!buildReference())
		{
			PDS_WARNING("adapt(): failed to buildReference()");
			return false;
		}
	}

	// backup old reference
	if (!_Reference.save(_Reference.getPath()+"ref"))
	{
		PDS_WARNING("adapt(): failed to backup reference index");
	}

	// create a new destination database
	CDatabase*	into = new CDatabase(_State.Id);

	if (!into->createFromScratch(description))
	{
		PDS_WARNING("adapt(): failed to create new reference");
		delete into;
		return NULL;
	}

	CDatabaseAdapter	adapter;

	if (!adapter.build(this, into))
	{
		PDS_WARNING("adapt(): failed to build() adapter");
		delete into;
		return NULL;
	}

	if (!adapter.buildContent())
	{
		PDS_WARNING("adapt(): adapter failed to buildContent()");
		delete into;
		return NULL;
	}

	// rebuild volatile data
	// that is all non persistant data that can be found from persistant data
	if (!into->rebuildVolatileData())
	{
		PDS_WARNING("adapt(): failed to rebuildVolatileData()");
		delete into;
		return NULL;
	}

	// init timestamps as database is ready to run
	into->initTimestamps();

	return into;
}
コード例 #12
0
/*
 * Update manager
 */
bool	CDbManager::update()
{
	H_AUTO(PDS_DbManager_update);

	CHECK_DB_MGR_INIT(update, false);

	// update stamp
	CTableBuffer::updateCommonStamp();

	TDatabaseMap::iterator	it;

	CDatabase::checkUpdateRates();


	// check evently if database need to write some delta
	TTime	tm = CTime::getLocalTime();
	if (tm >= _NextTimeDelta)
	{

		CTimestamp	starttime = _LastUpdateTime;
		CTimestamp	endtime;
		endtime.setToCurrent();

		std::vector<uint32>	ack;

		for (it=_DatabaseMap.begin(); it!=_DatabaseMap.end(); ++it)
		{
			CDatabase*	database = (*it).second;

			// generate deltas
			if (!database->buildDelta(starttime, endtime))
				nlwarning("failed to build delta for database '%d' '%s'", (*it).first, database->getName().c_str());

			// obsolete? since RBS build references and tells PDS of success/failure
			database->checkReferenceChange();

			// acknowledge last updates
			database->flushUpdates(ack);

			if (!ack.empty() && database->getMappedService().get() != 0xffff)
			{
				CMessage	msgack("PD_ACK_UPD");
				uint32		databaseId = (*it).first;
				msgack.serial(databaseId);
				msgack.serialCont(ack);
				CUnifiedNetwork::getInstance()->send(database->getMappedService(), msgack);
			}
		}

		_NextTimeDelta = tm - (tm%(DeltaUpdateRate*1000)) + (DeltaUpdateRate*1000);

		_LastUpdateTime = endtime;
	}

	CTimestamp	ts;
	ts.setToCurrent();

	// check databases require some delta packing/reference generation
	for (it=_DatabaseMap.begin(); it!=_DatabaseMap.end(); ++it)
	{
		CDatabase*	database = (*it).second;
		database->sendBuildCommands(ts);
	}

	// send messages to RBS if ready
	while (_RBSUp && !_RBSMessages.empty())
	{
		CUnifiedNetwork::getInstance()->send("RBS", *(_RBSMessages.front()));
		delete _RBSMessages.front();
		_RBSMessages.pop_front();
	}

	return true;
}
コード例 #13
0
ファイル: OleDBConnectionProp.cpp プロジェクト: malpharo/AiPI
bool COleDBConnectionProp::ReadProps(CDatabase& database)
{
	return ReadProps(database.GetConnect());
}
コード例 #14
0
ファイル: FoulerDoc.cpp プロジェクト: WisemanLim/femos
BOOL CFoulerDoc::OpenXLS(CString sFile)
{
	int i;
	double dData;
	CDatabase db;
	CString sSql;
	CString sItem;
	CString sDsn;
	CODBCFieldInfo fieldinfo;
	CMainFrame *pFrame = (CMainFrame*)AfxGetMainWnd();
	if( pFrame->m_strExcelDriver.IsEmpty() ) return FALSE;
	sDsn.Format("ODBC;DRIVER={%s};DSN='';DBQ=%s",pFrame->m_strExcelDriver,sFile);
	TRY
	{
		db.Open(NULL,FALSE,TRUE,sDsn);// Open the db using the former created pseudo DSN
		CRecordset rs( &db );// Allocate the recordset
		sSql = "SELECT * FROM Data";// Build the SQL string
		rs.Open(CRecordset::forwardOnly,sSql,CRecordset::readOnly);// Execute that query (implicitly by opening the recordset)
		CFieldSelect dlg(&rs);
		if( dlg.DoModal() == IDCANCEL )
		{
			rs.Close();
			db.Close();
			return FALSE;
		}
		BeginWaitCursor();
		while( !rs.IsEOF() ) rs.MoveNext();
		int iRecCount = (int)(rs.GetRecordCount());
		rs.Close();
		rs.Open(CRecordset::forwardOnly,sSql,CRecordset::readOnly);

		CProgressBar* pBar = new CProgressBar();
		ClearData();
		InsertData( iRecCount );
		for( i=0 ; i<iRecCount ; i++ )
		{
			rs.GetFieldValue(dlg.m_sField0,sItem);
			dData = atof(sItem)+dlg.m_dCo0;
			if( dlg.m_sField1 >= 0 && dlg.m_dCo1 != 0)
			{
				rs.GetFieldValue(dlg.m_sField1,sItem);
				dData += atof(sItem)*dlg.m_dCo1;
			}
			if( dlg.m_sField2 >= 0 && dlg.m_dCo2 != 0)
			{
				rs.GetFieldValue(dlg.m_sField2,sItem);
				dData += atof(sItem)*dlg.m_dCo2;
			}
			if( dlg.m_sField3 >= 0 && dlg.m_dCo3 != 0)
			{
				rs.GetFieldValue(dlg.m_sField3,sItem);
				dData += atof(sItem)*dlg.m_dCo3;
			}
			
			m_pOrgData[i]->SetItem( dData );
			m_iSubGroupIndex++;
			if( m_iSubGroupIndex >= m_iSubGroupSize )
			{
				m_iSubGroupIndex = 0;
				dData = 0;
				for( int j=i+1-m_iSubGroupSize ; j<i+1 ; j++ )
				{
					dData += m_pOrgData[j]->GetItem();
				}
				m_pData[i/m_iSubGroupSize]->SetItem(dData/m_iSubGroupSize);
			}
			rs.MoveNext();
			pBar->SetPos( (i<<8)/iRecCount );
		}
		delete pBar;
		rs.Close();
		db.Close();
		EndWaitCursor();
		return TRUE;
	}
	CATCH(CDBException, e)
	{
		return FALSE;// A db exception occured. Pop out the details...
	}
	END_CATCH;
}
コード例 #15
0
ファイル: Module.cpp プロジェクト: cherry-wb/upgradr
void*										
CUpgradrRootImpl::GetRawDB()
{
	CheckThreadOwnership(SR_DATABASE);
	return m_Database.GetRaw();
}
コード例 #16
0
ファイル: UpdateDB.cpp プロジェクト: eladkarako/locate32
int wmain (int argc,wchar_t ** argv)
{
	CAppData::stdfunc();
	
	_wsetlocale(LC_CTYPE,L".OCP"); 

	SetRegKey(argc,argv);

	if (!SetLanguageSpecifigHandles(argv[0]))
		return 1;

	CArrayFP<CDatabase*> aDatabases;
	
	WORD wCurrentThread=0;

	aDatabases.Add(CDatabase::FromDefaults(TRUE));
	aDatabases[0]->SetNamePtr(alloccopy(L"DEFAULTX"));
	aDatabases[0]->SetThreadId(wCurrentThread);

    int i,helps=0;
#ifndef WIN32
    if (getenv("TZ")==NULL)
		fprintf(stderr,"Timezone is not set. Database may contain invalid file times.\nFor example type "SET TZ=GMT+1" for central european time.\n");
#endif
    for (i=1;i<argc;i++)
    {
        if (argv[i][0]=='-' || argv[i][0]=='/')
        {
            switch (argv[i][1])
			{
			case L'X':
				if (argv[i][2]==L'\0')
				{
					if (i<argc-1)
						i++; // RegKeyName already set
				}
				break;
			case 'l':
			case 'L':
				if (wcsncmp(aDatabases.GetLast()->GetName(),L"PARAMX",6)!=0 && 
					wcsncmp(aDatabases.GetLast()->GetName(),L"DEFAULTX",8)!=0)
					wprintf(ID2W(IDS_UPDATEDB32CANNOTCHANGELOADED),aDatabases.GetLast()->GetName());
				else if (argv[i][2]=='1')
				{
					aDatabases.GetLast()->AddLocalRoots();
					aDatabases.GetLast()->SetNamePtr(alloccopy(L"PARAMX"));
				}
				else 
				{
					CStringW* pStr;
					if (argv[i][2]==L'\0' && i+1<argc)
						pStr=new CStringW(argv[++i]);
					else
						pStr=new CStringW(argv[i]+2);
					
					if ((*pStr)[0]==L'\"')
						pStr->DelChar(0);
					if (pStr->LastChar()==L'\"')
						pStr->DelLastChar();
					while (pStr->LastChar()==L'\\')
						pStr->DelLastChar();
					
					if (pStr->GetLength()>1)
					{
						pStr->ReplaceChars('/','\\');
						if ((*pStr)[1]==':' && pStr->GetLength()==2)
							aDatabases.GetLast()->AddRoot(pStr->GiveBuffer());
						else if (FileSystem::IsDirectory(*pStr))
							aDatabases.GetLast()->AddRoot(pStr->GiveBuffer());
						else
							fwprintf(stderr,ID2W(IDS_UPDATEDB32DIRECTORYISNOTVALID),(LPCWSTR)*pStr);
					}
					else
						fwprintf(stderr,ID2W(IDS_UPDATEDB32DIRECTORYISNOTVALID),(LPCWSTR)*pStr);
					delete pStr;

					aDatabases.GetLast()->SetNamePtr(alloccopy(L"PARAMX"));
				}
				break;
			case 'e':
				if (wcsncmp(aDatabases.GetLast()->GetName(),L"PARAMX",6)!=0 && 
					wcsncmp(aDatabases.GetLast()->GetName(),L"DEFAULTX",8)!=0)
					wprintf(ID2W(IDS_UPDATEDB32CANNOTCHANGELOADED),aDatabases.GetLast()->GetName());
				else 
				{
					CStringW* pStr;
					if (argv[i][2]=='\0' && i+1<argc)
						pStr=new CStringW(argv[++i]);
					else
						pStr=new CStringW(argv[i]+2);
					
					if ((*pStr)[0]==L'\"')
						pStr->DelChar(0);
					if (pStr->LastChar()==L'\"')
						pStr->DelLastChar();
					while (pStr->LastChar()==L'\\')
						pStr->DelLastChar();
					
					if (pStr->GetLength()>0)
						aDatabases.GetLast()->SetExcludedFiles(*pStr);

					aDatabases.GetLast()->SetNamePtr(alloccopy(L"PARAMX"));
				}
				break;
			case 'E':
				if (wcsncmp(aDatabases.GetLast()->GetName(),L"PARAMX",6)!=0 && 
					wcsncmp(aDatabases.GetLast()->GetName(),L"DEFAULTX",8)!=0)
					wprintf(ID2W(IDS_UPDATEDB32CANNOTCHANGELOADED),aDatabases.GetLast()->GetName());
				else 
				{
					CStringW* pStr;
					if (argv[i][2]=='\0' && i+1<argc)
						pStr=new CStringW(argv[++i]);
					else
						pStr=new CStringW(argv[i]+2);
					
					if ((*pStr)[0]==L'\"')
						pStr->DelChar(0);
					if (pStr->LastChar()==L'\"')
						pStr->DelLastChar();
					while (pStr->LastChar()==L'\\')
						pStr->DelLastChar();
					
					if (pStr->GetLength()>1)
					{
						pStr->ReplaceChars('/','\\');
						if (!aDatabases.GetLast()->AddExcludedDirectory(*pStr))
							fwprintf(stderr,ID2W(IDS_UPDATEDB32DIRECTORYISNOTVALID),(LPCWSTR)*pStr);
					}
					else
						fwprintf(stderr,ID2W(IDS_UPDATEDB32DIRECTORYISNOTVALID),(LPCWSTR)*pStr);
					delete pStr;

					aDatabases.GetLast()->SetNamePtr(alloccopy(L"PARAMX"));
				}
				break;
			case 't':
			case 'T':
				if (wcsncmp(aDatabases.GetLast()->GetName(),L"PARAMX",6)!=0 &&
					wcsncmp(aDatabases.GetLast()->GetName(),L"DEFAULTX",8)!=0)
					wprintf(ID2W(IDS_UPDATEDB32CANNOTCHANGELOADED),aDatabases.GetLast()->GetName());
				else if (argv[i][2]==L'c' || argv[i][2]==L'C')
				{
                       if (argv[i][3]==L'\0')
                           aDatabases.GetLast()->SetCreatorPtr(alloccopy(argv[++i]));
                       else
                           aDatabases.GetLast()->SetCreatorPtr(alloccopy(argv[i]+2));

					   aDatabases.GetLast()->SetNamePtr(alloccopy(L"PARAMX"));
				}
				else if (argv[i][2]==L'd' || argv[i][2]==L'D')
				{
                       if (argv[i][3]==L'\0')
                           aDatabases.GetLast()->SetDescriptionPtr(alloccopy(argv[++i]));
                       else
                           aDatabases.GetLast()->SetDescriptionPtr(alloccopy(argv[i]+2));

					   aDatabases.GetLast()->SetNamePtr(alloccopy(L"PARAMX"));
				}
				break;
			case 'i':
			case 'I':
				if (wcsncmp(aDatabases.GetLast()->GetName(),L"PARAMX",6)!=0 &&
					wcsncmp(aDatabases.GetLast()->GetName(),L"DEFAULTX",8)!=0)
					wprintf(ID2W(IDS_UPDATEDB32CANNOTCHANGELOADED),aDatabases.GetLast()->GetName());
				else
				{
                    aDatabases.GetLast()->SetFlag(CDatabase::flagIncrementalUpdate,TRUE);
					aDatabases.GetLast()->SetNamePtr(alloccopy(L"PARAMX"));
				}
				break;
			case 'c':
			case 'C':
				if (wcsncmp(aDatabases.GetLast()->GetName(),L"PARAMX",6)!=0 &&
					wcsncmp(aDatabases.GetLast()->GetName(),L"DEFAULTX",8)!=0)
					wprintf(ID2W(IDS_UPDATEDB32CANNOTCHANGELOADED),aDatabases.GetLast()->GetName());
				else if (argv[i][2]==L'A' || argv[i][2]==L'a')
				{
					aDatabases.GetLast()->SetFlag(CDatabase::flagAnsiCharset,TRUE);
					aDatabases.GetLast()->SetNamePtr(alloccopy(L"PARAMX"));
				}
				else if (argv[i][2]==L'U' || argv[i][2]==L'u')
				{
					aDatabases.GetLast()->SetFlag(CDatabase::flagAnsiCharset,FALSE);
					aDatabases.GetLast()->SetNamePtr(alloccopy(L"PARAMX"));
				}
				
				break;
			case 'N':
			case 'n':
				wCurrentThread++;
				break;
			case 'q':
			case 'Q':
				nQuiet=TRUE;
				break;
			case 'v':
			case 'V':
				printf("%s\n",szVersionStr);
				return 0;
			case 'd':
				{
					// Using database file
					CStringW sFile;
					if (argv[i][2]=='\0')
						sFile=argv[++i];
					else
						sFile=(argv[i]+2);
					sFile.ReplaceChars('/','\\');
					if (aDatabases.GetSize()==1 && wcscmp(aDatabases[0]->GetName(),L"DEFAULTX")==0)
					{
						aDatabases[0]->SetNamePtr(alloccopy(L"PARAMX"));
						aDatabases[0]->SetArchiveNamePtr(sFile.GiveBuffer());
					}
					else 
					{
						CDatabase* pDatabase=CDatabase::FromFile(sFile,(int)sFile.GetLength());
						if (pDatabase!=NULL)
						{
                            aDatabases.Add(pDatabase);
							pDatabase->SetNamePtr(alloccopy(L"PARAMX"));
							pDatabase->SetThreadId(wCurrentThread);
						}
					}
					

			
				}
				break;
			case 'D':
				{
					// Loading database 'name' from registry, cannot be changed 
					CStringW sName;
					if (argv[i][2]=='\0')
						sName=argv[++i];
					else
						sName=(argv[i]+2);

					if (CDatabase::FindByName(aDatabases,sName,(int)sName.GetLength())==NULL)
					{
						CDatabase* pDatabase=CDatabase::FromName(HKCU,
							CString(g_szRegKey)+"\\Databases",sName);

						if (pDatabase!=NULL)
						{
							pDatabase->SetFlag(CDatabase::flagGlobalUpdate);
							// Is only default loaded
							if (aDatabases.GetSize()==1 && wcscmp(aDatabases[0]->GetName(),L"DEFAULTX")==0)
							{
								delete aDatabases[0];
								aDatabases[0]=pDatabase;
							}
							else
							{
								aDatabases.Add(pDatabase);
								pDatabase->SetThreadId(wCurrentThread);
							}
						}
					}
				}
				break;
			case 'h':
			case 'H':
			case '?':
				helps=1;
				break;
			default:
				helps=1;
				break;
			}
       }
    }
    if (helps==1)
    {
#ifdef WIN32
		fprintf(stdout,"%s\n",szVersionStr);
#else
        fprintf(stdout,"%s\nusage updatedb",szVersionStr);
#endif

		HRSRC hRc=FindResource(GetLanguageSpecificResourceHandle(),MAKEINTRESOURCE(IDR_UPDATEDBHELP),"HELPTEXT");
		HGLOBAL hGlobal=LoadResource(GetLanguageSpecificResourceHandle(),hRc);
		LPCSTR pStr=(LPCSTR)LockResource(hGlobal);

		// Counting length
		int len;
		for (len=0;pStr[len]!='\0';len++)
		{
			if (pStr[len]=='E' && pStr[len+1]=='O' && pStr[len+2]=='F')
				break;
		}


		fwrite(pStr,1,len,stdout);
		
		FreeLibrary(GetLanguageSpecificResourceHandle());
		return 1;
    }

	// Checking databases
	// First, check that there is database 
	if (aDatabases.GetSize()==0)
		CDatabase::LoadFromRegistry(HKCU,CString(g_szRegKey)+"\\Databases",aDatabases);   
	else if (aDatabases.GetSize()==1 && wcsncmp(aDatabases[0]->GetName(),L"DEFAULTX",8)==0)
	{
		aDatabases.RemoveAll();
		CDatabase::LoadFromRegistry(HKCU,CString(g_szRegKey)+"\\Databases",aDatabases);   

		// No registry values?
		if (aDatabases.GetSize()==0)
		{
			aDatabases.Add(CDatabase::FromDefaults(TRUE));
			aDatabases[0]->SetNamePtr(alloccopy(L"DEFAULTX"));
		}
	}
		
		
	CDatabase::CheckValidNames(aDatabases);
	CDatabase::CheckDoubleNames(aDatabases);
	
	
	for (int i=0;i<aDatabases.GetSize();)
	{
		if (!aDatabases[i]->IsGloballyUpdated())
			aDatabases.RemoveAt(i);
		else 
		{
			if ((wcsncmp(aDatabases[i]->GetName(),L"PARAMX",6)==0 ||
				wcsncmp(aDatabases[i]->GetName(),L"DEFAULTX",8)==0))
			{
				BOOL bNameChanged=FALSE;
				if (aDatabases[i]->GetRoots()==0)
				{
					BOOL bFree;
					LPWSTR pFile=aDatabases[i]->GetResolvedArchiveName(bFree);
					CDatabaseInfo* pDatabaseInfo=CDatabaseInfo::GetFromFile(pFile);
					if (bFree)
						delete[] pFile;
					if (pDatabaseInfo!=NULL)
					{
						CDatabase* pDatabase;
						if (!pDatabaseInfo->sExtra2.IsEmpty())
							pDatabase=CDatabase::FromExtraBlock(pDatabaseInfo->sExtra2);
						if (pDatabase==NULL && !pDatabaseInfo->sExtra1.IsEmpty())
							pDatabase=CDatabase::FromExtraBlock(pDatabaseInfo->sExtra1);
						
						wprintf(ID2W(IDS_UPDATEDB32USINGEXISTINGSETTINGS),
							aDatabases[i]->GetArchiveName(),pDatabase->GetName());
						
						pDatabase->SetArchiveType(aDatabases[i]->GetArchiveType());
						pDatabase->SetArchiveName(aDatabases[i]->GetArchiveName());
						
						delete aDatabases[i];
						aDatabases[i]=pDatabase;

						delete pDatabaseInfo;
						bNameChanged=TRUE;
					}
				}

				if (!bNameChanged)
				{
					ULONG_PTR nFirst=LastCharIndex(aDatabases[i]->GetArchiveName(),L'\\')+1;
					int nLength=LastCharIndex(aDatabases[i]->GetArchiveName()+nFirst,L'.');
					if (nLength==-1)
						nLength=istrlenw(aDatabases[i]->GetArchiveName()+nFirst);

					

					aDatabases[i]->SetNamePtr(alloccopy(aDatabases[i]->GetArchiveName()+nFirst,nLength));
				}
			}

			
			i++;
		}
	}

	// Starting to update
	WORD dwTheads=CDatabase::CheckIDs(aDatabases);
    if (dwTheads==0)
	{
		FreeLibrary(GetLanguageSpecificResourceHandle());
		return FALSE;
	}
	if (dwTheads==1)
	{
		CDatabaseUpdater Updater(aDatabases,aDatabases.GetSize(),UpdateProc);
		Updater.Update(FALSE);
	}
	else
	{
		WORD wThread;

		ppUpdaters=new CDatabaseUpdater*[dwTheads+1];

		for (wThread=0;wThread<dwTheads;wThread++)
		{
			ppUpdaters[wThread]=new CDatabaseUpdater(aDatabases,aDatabases.GetSize(),							
				UpdateProc,wThread,(DWORD)0);
		}
		ppUpdaters[dwTheads]=NULL;

		// Starting
		DWORD dwRunning=0;
		UpdateError ueCode;
		for (wThread=0;wThread<dwTheads;wThread++)
		{
			ueCode=ppUpdaters[wThread]->Update(TRUE);
			if (ueCode==ueSuccess)
				dwRunning++;
			else
			{
				delete ppUpdaters[wThread];
				ppUpdaters[wThread]=UPDATER_EXITED(ueCode);
			}
		}
		
		if (dwRunning==0)
			delete ppUpdaters;
		else
		{
			while (ppUpdaters!=NULL)
				Sleep(100);
		}
	}

	FinishRegKey();

	FreeLibrary(GetLanguageSpecificResourceHandle());

	return 1;
}
コード例 #17
0
ファイル: mainui.cpp プロジェクト: rranjan308/ILP-Project
void CMainUI::login(CDatabase &a)
{
string suname,spwd,sbrid;
vector <CUserlogin> records;
do
{
system("clear");
cout<<cyan<<"------------------------------------------------------------------------------------------------\n"<<white;
cout<<cyan<<"------------------------------------------------------------------------------------------------\n"<<white;
cout<<cyan<<"------------------------------------------------------------------------------------------------\n"<<white;
cout<<blink<<"------------------------------------------------------------------------------------------------\n"<<white;
cout<<"                   *******     *****   "<<red<<"      |****   "<<white<<endl
    <<"                   ********   *******  "<<red<<"      |****   "<<white<<endl               
    <<"                         **   **       "<<red<<"      |****  " <<white<<endl
    <<"                         **     **     "<<red<<" _____|****    "<<white<<endl
    <<"                    *******       **   "<<red<<" ****************    "<<white<<endl
    <<"                    *******         ** "<<red<<" ****************    "<<white<<endl
    <<"                         **         ** "<<red<<" ****************   " <<white<<endl
    <<"                         **        **  "<<red<<"       ****    "<<white<<endl
    <<"                   ********   *******  "<<red<<"       ****   "<<white<<endl
    <<"                   *******     *****   "<<red<<"       ****  "<<white<<endl
    <<"                                       "<<red<<"       **** "<<blue<<"copyright@SWASTIK SUPER SPECIALITY HOSPITAL "<<white<<endl; 


cout<<blink<<"-------------------------------------------------------------------------------------------------\n"<<white;
cout<<cyan<<"--------------------------------------------------------------------------------------------------\n"<<white;
cout<<cyan<<"--------------------------------------------------------------------------------------------------\n"<<white;
cout<<cyan<<"--------------------------------------------------------------------------------------------------\n"<<white;
cout<<cyan<<"--------------------------------------------------------------------------------------------------\n"<<white;


cout<<yellow<<"\n\t\t\t\tEnter username: "******"\n\t\t\t\tEnter Password: "******"Receptionist")
		{
//		cout<<yellow<<"\nReceptionist is looged on"<<white;
	//	CPatientui cui;
                sbrid=(*iter).getBranchid();
		cui.setBrId(sbrid);
		cui.displayMenu();
		}
		if(((*iter).getDesignation())=="Doctor")
                {
		string did=(*iter).getUsername();
  //              cout<<yellow<<"\nDoctor is looged on"<<white;
	//	CPatientui cui;
		cui.setDocId(did);
                cui.displayMenudoctor();
                }
		if(((*iter).getDesignation())=="Chairman")
                {
		string did=(*iter).getUsername();
    //            cout<<yellow<<"\nChairman is looged on"<<white;
	//	CPatientui cui;
		sbrid=(*iter).getBranchid();
		eui.setBrId(sbrid);
		seui.setBrId(sbrid);
                eui.displaymenu();
                }
		
		if(((*iter).getDesignation())=="Pharmacist")
                {
		string did=(*iter).getUsername();
      //          cout<<yellow<<"\nPharmacist is looged on"<<white;
	//	CPatientui cui;
		sbrid=(*iter).getBranchid();
		sui.setBrId(sbrid);
                sui.displayMenu();
                }
              


        }
	}
else
        {
        cout<<red<<"\nInvalid Username or password"<<white;
	cout<<"\n\n";
	getpass("Press Enter to continue to Login Screen");
        }
}while(records.size()==0);
}
コード例 #18
0
void CNormalPF::CalculateAccelerate(int nIndex, int nTick, double* pdAccX, double* pdAccY)
{
	CDatabase* pDatabase = CDatabase::GetInstance();

	int nNumAdjVehicles = pDatabase->GetNumAdjacentVehicles();

	//! For repulsive energy
	double dCoefficientG = 5.0;
	double dCoefficientO = 200.0;
	double dCorrelationG = 20.0;
	double dCorrelationO = 5.0;

	//! Own vehicleの位置を計算する.
	double dOwnPosX = pDatabase->GetData(CDatabase::SIMULATION, nTick - 1, nIndex, PACKET_SIMUL_POSX);
	double dOwnPosY = pDatabase->GetData(CDatabase::SIMULATION, nTick - 1, nIndex, PACKET_SIMUL_POSY);
	double dOwnVelX = pDatabase->GetData(CDatabase::SIMULATION, nTick - 1, nIndex, PACKET_SIMUL_VELX);
	double dOwnVelY = pDatabase->GetData(CDatabase::SIMULATION, nTick - 1, nIndex, PACKET_SIMUL_VELY);
	int nOwnLane = (dOwnPosY - 0.5*LANE_WIDTH) / LANE_WIDTH;

	
	//! 前後を走行する車両を検出する
	double dMinDistance = DBL_MAX;
	double dRelVelX = 0.0;

	for (int n = 0; n < nNumAdjVehicles; n++)
	{
		if (n == nIndex)
			continue;

		double dPosX = pDatabase->GetData(CDatabase::SIMULATION, nTick - 1, n, PACKET_SIMUL_POSX);
		double dPosY = pDatabase->GetData(CDatabase::SIMULATION, nTick - 1, n, PACKET_SIMUL_POSY);
		double dVelX = pDatabase->GetData(CDatabase::SIMULATION, nTick - 1, n, PACKET_SIMUL_VELX);
		double dVelY = pDatabase->GetData(CDatabase::SIMULATION, nTick - 1, n, PACKET_SIMUL_VELY);
		int nLane = (dPosY - 0.5*LANE_WIDTH) / LANE_WIDTH;

		//! 周辺車両が自車より後ろにいる場合は考慮しない
		if ((dPosX - dOwnPosX) < 0.0)
			continue;

		if (nLane != nOwnLane)
			continue;

		double dDistance = qAbs(dPosX - dOwnPosX);

		if (dDistance < dMinDistance)
		{
			dMinDistance = dDistance;
			dRelVelX = dVelX - dOwnVelX;
		}
	}

	double dDistanceOfGoal = 0.0;
	double dDistanceOfObstacle = 0.0;

	if (dMinDistance == DBL_MAX)
	{
		*pdAccX = 0.0;
		*pdAccY = 0.0;

		return;
	}
	else
	{
		dDistanceOfObstacle = dMinDistance;
		dDistanceOfGoal = dDistanceOfObstacle + 10.0;
	}

	double dForceX = (2 * dCoefficientO * dDistanceOfObstacle) / (dCorrelationO*dCorrelationO) * qExp(-dDistanceOfObstacle*dDistanceOfObstacle / (dCorrelationO*dCorrelationO)) * (1 - qExp(-dDistanceOfGoal*dDistanceOfGoal / (dCorrelationG*dCorrelationG)));
	double dForceX2 = dCoefficientO * qExp(-dDistanceOfObstacle*dDistanceOfObstacle / (dCorrelationO*dCorrelationO))*(-2 * dDistanceOfGoal / (dCorrelationG*dCorrelationG)*qExp(-dDistanceOfGoal*dDistanceOfGoal / (dCorrelationG*dCorrelationG)));
	double dForceX3 = -(2 * dCoefficientG*dDistanceOfGoal / (dCorrelationG*dCorrelationG))*qExp(-dDistanceOfGoal*dDistanceOfGoal / (dCorrelationG*dCorrelationG));

	double dPotential1 = calcPotential(nIndex, nTick, dOwnPosX, dOwnPosY);
	double dPotential2 = calcPotential(nIndex, nTick, dOwnPosX+0.001, dOwnPosY);

	double dCheck = -(dPotential2 - dPotential1) / 0.001;
	double dCheck2 = -(dForceX + dForceX2 + dForceX3);

	//! 求まった加速度を記録する
	*pdAccX = -(dForceX + dForceX2 + dForceX3);
	*pdAccY = 0.0;
}
コード例 #19
0
ファイル: AccountDetail.cpp プロジェクト: ShipuW/ebank-MFC
void AccountDetail::OnClickedRadioDeposit()//////////////////////////////////////切换查看类型
{
	UpdateData(TRUE);
	switch (m_DetailradioType)
	{
	case 0:
	{
			  CString sqlstr;
			  sqlstr.Format(_T("select money_value,operate_time from operate_deposit where card_number ='%s'"), CardDetail);
			  AccountOperate.DeleteAllItems();

			  CDatabase db;
			  db.Open("bankmanagement");
			  CRecordset rs(&db);
			  rs.Open(CRecordset::forwardOnly, (_T("%s"), sqlstr));
			  while (!rs.IsEOF())
			  {
				  CString varOperateType;
				  varOperateType = "存款";
				  AccountOperate.InsertItem(0, varOperateType);
				  CString varOperateAmount;
				  rs.GetFieldValue(_T("money_value"), varOperateAmount);
				  AccountOperate.SetItemText(0, 1, varOperateAmount);
				  CString varOperateTime;
				  rs.GetFieldValue(_T("operate_time"), varOperateTime);
				  AccountOperate.SetItemText(0, 2, varOperateTime);
				  rs.MoveNext();
			  }
			  rs.Close();
			  AccountOperate.SetExtendedStyle(LVS_EX_FLATSB | LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES);
			  break;
	}
	case 1:
	{
			  CString sqlstr;
			  sqlstr.Format(_T("select money_value,operate_time from operate_draw where card_number ='%s'"), CardDetail);
			  AccountOperate.DeleteAllItems();

			  CDatabase db;
			  db.Open("bankmanagement");
			  CRecordset rs(&db);
			  rs.Open(CRecordset::forwardOnly, (_T("%s"), sqlstr));
			  while (!rs.IsEOF())
			  {
				  CString varOperateType;
				  varOperateType = "取款";
				  AccountOperate.InsertItem(0, varOperateType);
				  CString varOperateAmount;
				  rs.GetFieldValue(_T("money_value"), varOperateAmount);
				  AccountOperate.SetItemText(0, 1, varOperateAmount);
				  CString varOperateTime;
				  rs.GetFieldValue(_T("operate_time"), varOperateTime);
				  AccountOperate.SetItemText(0, 2, varOperateTime);
				  rs.MoveNext();
			  }
			  rs.Close();
			  AccountOperate.SetExtendedStyle(LVS_EX_FLATSB | LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES);
			  break;
	}
	case 2:
	{
			  CString sqlstr;
			  sqlstr.Format(_T("select money_value,operate_time from operate_transfer where card_number_from ='%s'"), CardDetail);
			  AccountOperate.DeleteAllItems();

			  CDatabase db;
			  db.Open("bankmanagement");
			  CRecordset rs(&db);
			  rs.Open(CRecordset::forwardOnly, (_T("%s"), sqlstr));
			  while (!rs.IsEOF())
			  {
				  CString varOperateType;
				  varOperateType = "转账";
				  AccountOperate.InsertItem(0, varOperateType);
				  CString varOperateAmount;
				  rs.GetFieldValue(_T("money_value"), varOperateAmount);
				  AccountOperate.SetItemText(0, 1, varOperateAmount);
				  CString varOperateTime;
				  rs.GetFieldValue(_T("operate_time"), varOperateTime);
				  AccountOperate.SetItemText(0, 2, varOperateTime);
				  rs.MoveNext();
			  }
			  rs.Close();
			  AccountOperate.SetExtendedStyle(LVS_EX_FLATSB | LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES);
	}
	}
	// TODO:  在此添加控件通知处理程序代码
}
コード例 #20
0
CStdString CSmartPlaylistRule::GetWhereClause(CDatabase &db, const CStdString& strType)
{
  SEARCH_OPERATOR op = m_operator;
  if ((strType == "tvshows" || strType == "episodes") && m_field == FIELD_YEAR)
  { // special case for premiered which is a date rather than a year
    // TODO: SMARTPLAYLISTS do we really need this, or should we just make this field the premiered date and request a date?
    if (op == OPERATOR_EQUALS)
      op = OPERATOR_CONTAINS;
    else if (op == OPERATOR_DOES_NOT_EQUAL)
      op = OPERATOR_DOES_NOT_CONTAIN;
  }
  CStdString operatorString, negate;
  CStdString parameter;
  if (GetFieldType(m_field) == TEXTIN_FIELD)
  {
    CStdStringArray split;
    StringUtils::SplitString(m_parameter, ",", split);
    for (CStdStringArray::iterator it=split.begin(); it!=split.end(); ++it)
    {
      if (!parameter.IsEmpty())
        parameter += ",";
      parameter += db.PrepareSQL("'%s'", (*it).Trim().c_str());
    }
    parameter = " IN (" + parameter + ")";
    if (op == OPERATOR_DOES_NOT_EQUAL)
      negate = " NOT";
  }
  else
  {
    // the comparison piece
    switch (op)
    {
    case OPERATOR_CONTAINS:
      operatorString = " LIKE '%%%s%%'"; break;
    case OPERATOR_DOES_NOT_CONTAIN:
      negate = " NOT"; operatorString = " LIKE '%%%s%%'"; break;
    case OPERATOR_EQUALS:
      operatorString = " LIKE '%s'"; break;
    case OPERATOR_DOES_NOT_EQUAL:
      negate = " NOT"; operatorString = " LIKE '%s'"; break;
    case OPERATOR_STARTS_WITH:
      operatorString = " LIKE '%s%%'"; break;
    case OPERATOR_ENDS_WITH:
      operatorString = " LIKE '%%%s'"; break;
    case OPERATOR_AFTER:
    case OPERATOR_GREATER_THAN:
    case OPERATOR_IN_THE_LAST:
      operatorString = " > '%s'"; break;
    case OPERATOR_BEFORE:
    case OPERATOR_LESS_THAN:
    case OPERATOR_NOT_IN_THE_LAST:
      operatorString = " < '%s'"; break;
    case OPERATOR_TRUE:
      operatorString = " = 1"; break;
    case OPERATOR_FALSE:
      negate = " NOT "; operatorString = " = 0"; break;
    default:
      break;
    }

    parameter = db.PrepareSQL(operatorString.c_str(), m_parameter.c_str());
  }

  if (m_field == FIELD_LASTPLAYED)
  {
    if (m_operator == OPERATOR_IN_THE_LAST || m_operator == OPERATOR_NOT_IN_THE_LAST)
    { // translate time period
      CDateTime date=CDateTime::GetCurrentDateTime();
      CDateTimeSpan span;
      span.SetFromPeriod(m_parameter);
      date-=span;
      parameter = db.PrepareSQL(operatorString.c_str(), date.GetAsDBDate().c_str());
    }
  }
  else if (m_field == FIELD_TIME)
  { // translate time to seconds
    CStdString seconds; seconds.Format("%i", StringUtils::TimeStringToSeconds(m_parameter));
    parameter = db.PrepareSQL(operatorString.c_str(), seconds.c_str());
  }

  // now the query parameter
  CStdString query;
  if (strType == "songs")
  {
    if (m_field == FIELD_GENRE)
      query = negate + " ((strGenre" + parameter + ") or idSong IN (select idSong from genre,exgenresong where exgenresong.idGenre = genre.idGenre and genre.strGenre" + parameter + "))";
    else if (m_field == FIELD_ARTIST)
      query = negate + " ((strArtist" + parameter + ") or idSong IN (select idSong from artist,exartistsong where exartistsong.idArtist = artist.idArtist and artist.strArtist" + parameter + "))";
    else if (m_field == FIELD_ALBUMARTIST)
      query = negate + " (idalbum in (select idalbum from artist,album where album.idArtist=artist.idArtist and artist.strArtist" + parameter + ") or idalbum in (select idalbum from artist,exartistalbum where exartistalbum.idArtist = artist.idArtist and artist.strArtist" + parameter + "))";
    else if (m_field == FIELD_LASTPLAYED && (m_operator == OPERATOR_LESS_THAN || m_operator == OPERATOR_BEFORE || m_operator == OPERATOR_NOT_IN_THE_LAST))
      query = "lastPlayed is NULL or lastPlayed" + parameter;
  }
  else if (strType == "albums")
  {
    if (m_field == FIELD_GENRE)
      query = negate + " (idAlbum in (select song.idAlbum from song join genre on song.idGenre=genre.idGenre where genre.strGenre" + parameter + ") or "
              "idAlbum in (select song.idAlbum from song join exgenresong on song.idSong=exgenresong.idSong join genre on exgenresong.idGenre=genre.idGenre where genre.strGenre" + parameter + "))";
    else if (m_field == FIELD_ARTIST)
      query = negate + " (idAlbum in (select song.idAlbum from song join artist on song.idArtist=artist.idArtist where artist.strArtist" + parameter + ") or "
              "idAlbum in (select song.idAlbum from song join exartistsong on song.idSong=exartistsong.idSong join artist on exartistsong.idArtist=artist.idArtist where artist.strArtist" + parameter + "))";
    else if (m_field == FIELD_ALBUMARTIST)
      query = negate + " (idalbum in (select idalbum from artist,album where album.idArtist=artist.idArtist and artist.strArtist" + parameter + ") or idalbum in (select idalbum from artist,exartistalbum where exartistalbum.idArtist = artist.idArtist and artist.strArtist" + parameter + "))";
  }
  else if (strType == "movies")
  {
    if (m_field == FIELD_GENRE)
      query = "idMovie" + negate + " in (select idMovie from genrelinkmovie join genre on genre.idGenre=genrelinkmovie.idGenre where genre.strGenre" + parameter + ")";
    else if (m_field == FIELD_DIRECTOR)
      query = "idMovie" + negate + " in (select idMovie from directorlinkmovie join actors on actors.idActor=directorlinkmovie.idDirector where actors.strActor" + parameter + ")";
    else if (m_field == FIELD_ACTOR)
      query = "idMovie" + negate + " in (select idMovie from actorlinkmovie join actors on actors.idActor=actorlinkmovie.idActor where actors.strActor" + parameter + ")";
    else if (m_field == FIELD_WRITER)
      query = "idMovie" + negate + " in (select idMovie from writerlinkmovie join actors on actors.idActor=writerlinkmovie.idWriter where actors.strActor" + parameter + ")";
    else if (m_field == FIELD_STUDIO)
      query = "idMovie" + negate + " in (select idMovie from studiolinkmovie join studio on studio.idStudio=studiolinkmovie.idStudio where studio.strStudio" + parameter + ")";
    else if (m_field == FIELD_COUNTRY)
      query = "idMovie" + negate + " in (select idMovie from countrylinkmovie join country on country.idCountry=countrylinkmovie.idCountry where country.strCountry" + parameter + ")";
    else if (m_field == FIELD_HASTRAILER)
      query = negate + GetDatabaseField(m_field, strType) + "!= ''";
    else if (m_field == FIELD_LASTPLAYED && (m_operator == OPERATOR_LESS_THAN || m_operator == OPERATOR_BEFORE || m_operator == OPERATOR_NOT_IN_THE_LAST))
      query = "lastPlayed is NULL or lastPlayed" + parameter;
    else if (m_field == FIELD_INPROGRESS)
      query = "idFile " + negate + " in (select idFile from bookmark where type = 1)";
  }
  else if (strType == "musicvideos")
  {
    if (m_field == FIELD_GENRE)
      query = "idMVideo" + negate + " in (select idMVideo from genrelinkmusicvideo join genre on genre.idGenre=genrelinkmusicvideo.idGenre where genre.strGenre" + parameter + ")";
    else if (m_field == FIELD_ARTIST)
      query = "idMVideo" + negate + " in (select idMVideo from artistlinkmusicvideo join actors on actors.idActor=artistlinkmusicvideo.idArtist where actors.strActor" + parameter + ")";
    else if (m_field == FIELD_STUDIO)
      query = "idMVideo" + negate + " in (select idMVideo from studiolinkmusicvideo join studio on studio.idStudio=studiolinkmusicvideo.idStudio where studio.strStudio" + parameter + ")";
    else if (m_field == FIELD_DIRECTOR)
      query = "idMVideo" + negate + " in (select idMVideo from directorlinkmusicvideo join actors on actors.idActor=directorlinkmusicvideo.idDirector where actors.strActor" + parameter + ")";
    else if (m_field == FIELD_LASTPLAYED && (m_operator == OPERATOR_LESS_THAN || m_operator == OPERATOR_BEFORE || m_operator == OPERATOR_NOT_IN_THE_LAST))
      query = "lastPlayed is NULL or lastPlayed" + parameter;
  }
  else if (strType == "tvshows")
  {
    if (m_field == FIELD_GENRE)
      query = "tvshow.idShow" + negate + " in (select idShow from genrelinktvshow join genre on genre.idGenre=genrelinktvshow.idGenre where genre.strGenre" + parameter + ")";
    else if (m_field == FIELD_DIRECTOR)
      query = "tvshow.idShow" + negate + " in (select idShow from directorlinktvshow join actors on actors.idActor=directorlinktvshow.idDirector where actors.strActor" + parameter + ")";
    else if (m_field == FIELD_ACTOR)
      query = "tvshow.idShow" + negate + " in (select idShow from actorlinktvshow join actors on actors.idActor=actorlinktvshow.idActor where actors.strActor" + parameter + ")";
  }
  else if (strType == "episodes")
  {
    if (m_field == FIELD_GENRE)
      query = "idShow" + negate + " in (select idShow from genrelinktvshow join genre on genre.idGenre=genrelinktvshow.idGenre where genre.strGenre" + parameter + ")";
    else if (m_field == FIELD_DIRECTOR)
      query = "idEpisode" + negate + " in (select idEpisode from directorlinkepisode join actors on actors.idActor=directorlinkepisode.idDirector where actors.strActor" + parameter + ")";
    else if (m_field == FIELD_ACTOR)
      query = "idEpisode" + negate + " in (select idEpisode from actorlinkepisode join actors on actors.idActor=actorlinkepisode.idActor where actors.strActor" + parameter + ")";
    else if (m_field == FIELD_WRITER)
      query = "idEpisode" + negate + " in (select idEpisode from writerlinkepisode join actors on actors.idActor=writerlinkepisode.idWriter where actors.strActor" + parameter + ")";
    else if (m_field == FIELD_LASTPLAYED && (m_operator == OPERATOR_LESS_THAN || m_operator == OPERATOR_BEFORE || m_operator == OPERATOR_NOT_IN_THE_LAST))
      query = "lastPlayed is NULL or lastPlayed" + parameter;
    else if (m_field == FIELD_INPROGRESS)
      query = "idFile " + negate + " in (select idFile from bookmark where type = 1)";
  }
  if (m_field == FIELD_VIDEORESOLUTION)
    query = "idFile" + negate + GetVideoResolutionQuery();
  else if (m_field == FIELD_AUDIOCHANNELS)
    query = "idFile" + negate + " in (select distinct idFile from streamdetails where iAudioChannels " + parameter + ")";
  else if (m_field == FIELD_VIDEOCODEC)
    query = "idFile" + negate + " in (select distinct idFile from streamdetails where strVideoCodec " + parameter + ")";
  else if (m_field == FIELD_AUDIOCODEC)
    query = "idFile" + negate + " in (select distinct idFile from streamdetails where strAudioCodec " + parameter + ")";
  else if (m_field == FIELD_AUDIOLANGUAGE)
    query = "idFile" + negate + " in (select distinct idFile from streamdetails where strAudioLanguage " + parameter + ")";
  else if (m_field == FIELD_SUBTITLELANGUAGE)
    query = "idFile" + negate + " in (select distinct idFile from streamdetails where strSubtitleLanguage " + parameter + ")";
  else if (m_field == FIELD_VIDEOASPECT)
    query = "idFile" + negate + " in (select distinct idFile from streamdetails where fVideoAspect " + parameter + ")";
  else if (m_field == FIELD_PLAYLIST)
  { // playlist field - grab our playlist and add to our where clause
    CStdString playlistFile = CSmartPlaylistDirectory::GetPlaylistByName(m_parameter, strType);
    if (!playlistFile.IsEmpty())
    {
      CSmartPlaylist playlist;
      playlist.Load(playlistFile);
      CStdString playlistQuery;
      // only playlists of same type will be part of the query
      if (playlist.GetType().Equals(strType) || (playlist.GetType().Equals("mixed") && (strType == "songs" || strType == "musicvideos")) || playlist.GetType().IsEmpty())
      {
        playlist.SetType(strType);
        playlistQuery = playlist.GetWhereClause(db, false);
      }
      if (m_operator == OPERATOR_DOES_NOT_EQUAL && playlist.GetType().Equals(strType))
        query.Format("NOT (%s)", playlistQuery.c_str());
      else if (m_operator == OPERATOR_EQUALS && playlist.GetType().Equals(strType))
        query = playlistQuery;
    }
  }
  if (m_field == FIELD_PLAYCOUNT && strType != "songs" && strType != "albums")
  { // playcount is stored as NULL or number in video db
    if ((m_operator == OPERATOR_EQUALS && m_parameter == "0") ||
        (m_operator == OPERATOR_DOES_NOT_EQUAL && m_parameter != "0") ||
        (m_operator == OPERATOR_LESS_THAN))
    {
      CStdString field = GetDatabaseField(FIELD_PLAYCOUNT, strType);
      query = field + " is NULL or " + field + parameter;
    }
  }
  if (query.IsEmpty() && m_field != FIELD_NONE)
    query = GetDatabaseField(m_field,strType) + negate + parameter;
  // if we fail to get a dbfield, we empty query so it doesn't fail
  if (query.Equals(negate + parameter))
    query = "";
  return query;
}
コード例 #21
0
ファイル: fmserver.cpp プロジェクト: jbailhache/log
void fmserver (void)
{
	struct fmparam param[1];

	// MessageBox (NULL, "Hello", "Message", MB_OK);

	init_param(param);
	
	/* test

	CDatabase db;
	db.OpenEx (_T("DSN=droits"), 0);

	CRecordsetClients rs;

	rs.Open (AFX_DB_USE_DEFAULT_TYPE, "SELECT * FROM clients", 0);
	rs.MoveFirst();
	for (;;)
	{
		if (rs.IsEOF())
			break;
		MessageBox (NULL, rs.m_login, "Login", MB_OK);
		rs.MoveNext();
	}

	rs.Close();

	*/

	WSADATA wsda;
	SOCKET sListen, sClient;
	struct hostent * hp;
	char buf[10000];
	int len;
	SOCKADDR_IN addr, remote_addr;
	int ret;
	int iAddrLen;

	WSAStartup (MAKEWORD(1,1), &wsda);

	hp = gethostbyname ("localhost");

	/*sListen = socket (hp->h_addrtype, SOCK_STREAM, 0);*/

	sListen = socket (AF_INET, SOCK_STREAM, 0 /*IPPROTO_IP*/);
	if (sListen == SOCKET_ERROR)
	{
		MessageBox (NULL, "Error creating socket", "Error", MB_OK);
		exit(0);
	}

	memset (&addr, 0, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_port = htons(6030);
	addr.sin_addr.s_addr = htonl (INADDR_ANY);

	ret = bind (sListen, (struct sockaddr *)&addr, sizeof(addr));
	if (ret == SOCKET_ERROR)
	{
		MessageBox (NULL, "Error bind", "Error", MB_OK);
		exit(0);
	}

	ret = listen (sListen, 10);
	if (ret == SOCKET_ERROR)
	{
		sprintf (buf, "Error listen: %d", WSAGetLastError());		
		MessageBox (NULL, buf, "Error listen", MB_OK);
		exit(0);
	}

	for (;;)
	{

	iAddrLen = sizeof(remote_addr);

	sClient = accept (sListen, (struct sockaddr *) &remote_addr, &iAddrLen);
	if (sClient == SOCKET_ERROR)
	{
		MessageBox (NULL, "Error accept", "Error", MB_OK);
		exit(0);
	}

	// MessageBox (NULL, "Accepted", "server", MB_OK);

	/*
	ret = recv (sClient, buf, sizeof(buf), 0);
	if (ret == SOCKET_ERROR)
	{
		MessageBox (NULL, "Error recv", "Error", MB_OK);
		exit(0);
	}
	buf[ret] = 0;

	MessageBox (NULL, buf, "Received", MB_OK);
	*/

	/*
	input (sClient, buf);
	MessageBox (NULL, buf, "received", MB_OK);
	*/

	char dirfax[100];
	char basedroits[100];
	char basefax[100];
	char faxdir[100];
	char language[100];
	char login[100];
	char pass[100];

	strcpy (basedroits, "droits");
	strcpy (basefax, "AT05");
	strcpy (faxdir, "L:\\AT05");


	for (;;)
	{
		input (sClient, buf);
		if (status == SOCKET_ERROR)
			break;

		// MessageBox (NULL, buf, "commande", MB_OK);
	
		if (!strcmp (buf, "BASEFAX"))
		{
			input (sClient, dirfax);
			input (sClient, language);
			
			if (*dirfax)
			{
				lire_fichier (dirfax, "baserights.txt", basedroits);
				lire_fichier (dirfax, "basefax.txt", basefax);
				lire_fichier (dirfax, "faxdir.txt", faxdir);
			}

			output (sClient, "ID\tIdentifiant\t30\n");
			output (sClient, "CNX\tDate\t20\n");
			output (sClient, "TIME\tDurée\t5\n");
			output (sClient, "PGENB\tPages\t5\n");
			output (sClient, "HGN\tStatus\t5\n");
			output (sClient, "FILE\tFichier\t15\n");
			output (sClient, "\n");
		 
		}
		else if (!strcmp (buf, "USER"))
		{
			input (sClient, login);
		}
		else if (!strcmp (buf, "PASS"))
		{
			input (sClient, pass);
			output (sClient, "LOGIN\n1\n");
		}
		
		else if (!strcmp (buf, "LISTREC"))
		{
			
			char param[100];
			char strsince[100];
			input (sClient, param);
			input (sClient, strsince);

			CDatabase db;
			char dsn[100];
			sprintf (dsn, "DSN=%s", basefax);
			db.OpenEx (_T(dsn), 0);

			CRecordsetRec rs;

			rs.Open (AFX_DB_USE_DEFAULT_TYPE, "SELECT * FROM REC", 0);
			rs.MoveFirst();

			// MessageBox (NULL, "Reading base", "trace", MB_OK);

			for (;;)
			{
				if (rs.IsEOF())
					break;
				/*MessageBox (NULL, rs.m_ID, "id", MB_OK);*/
				sprintf (buf, 
 "<MESSAGE><BASE>FAXBT</BASE><ID>%s</ID><CNX>%s</CNX><TIME>%lf</TIME><PGENB>%lf</PGENB><HGN>%lf</HGN><FILE>%s</FILE></MESSAGE>\n",
								LPCSTR(rs.m_ID), 
								LPCSTR(rs.m_CNX), 
								rs.m_TIME, 
								rs.m_PGENB, 
								rs.m_HGN,
								LPCSTR(rs.m_FILE));
				/*MessageBox (NULL, buf, "Message", MB_OK);*/
				output (sClient, buf);
				rs.MoveNext();
			}
			output (sClient, "\n");

			rs.Close();



		}
		else if (!strcmp (buf, "END"))
		{
			// MessageBox (NULL, buf, "END", MB_OK);
			break;
		}
		else
		{
			// MessageBox (NULL, buf, "autre commande", MB_OK);
		}


	}

	closesocket (sClient);

	}
/*
	for (;;)
	{
		input (commande);
		MessageBox (NULL, commande, "Commande", MB_OK);

	}
*/

}