Beispiel #1
0
static HRESULT ProcessVariable(__in FILE *fp, __in WORD nIndex, __in TYPEATTR* lpTypeAttr,
                               __in ITypeInfo *lpTypeInfo, __in SIZE_T nIndent)
{
  CAutoVarDesc cVarDesc;
  CNktStringW cStrTempW;
  CNktComBStr bstrMemberName;
  BSTR bstr;
  HRESULT hRes;
  UINT nNamesCount;
  WORD i;
  char szBufA[32];

  hRes = cVarDesc.Set(lpTypeInfo, nIndex);
  EXIT_ON_ERROR(hRes);
  if (cVarDesc->varkind == VAR_CONST)
  {
    _tprintf_s(_T("Error: Variables should not be constants.\n"));
    return E_NOTIMPL;
  }
  hRes = lpTypeInfo->GetNames(cVarDesc->memid, &bstr, 1, &nNamesCount);
  EXIT_ON_ERROR(hRes);
  if (nNamesCount == 0 || bstr == NULL)
  {
    _tprintf_s(_T("Error: Unnamed variables are not supported.\n"));
    return E_NOTIMPL;
  }
  bstrMemberName.Attach(bstr);
  WRITEINDENT_AND_CHECK(fp, nIndent);
  if ((cVarDesc->elemdescVar.tdesc.vt & 0x0FFF) == VT_CARRAY)
  {
    // type name[n]
    cStrTempW.Empty();
    hRes = TypeDescToString(cStrTempW, &(cVarDesc->elemdescVar.tdesc.lpadesc->tdescElem), lpTypeInfo,
                            FALSE);
    EXIT_ON_ERROR(hRes);
    WRITEWIDE_AND_CHECK(fp, (LPWSTR)cStrTempW);
    WRITEANSI_AND_CHECK(fp, " ");
    WRITEBSTR_AND_CHECK(fp, bstrMemberName);
    for (i=0; i<cVarDesc->elemdescVar.tdesc.lpadesc->cDims; i++)
    {
      _snprintf_s(szBufA, X_ARRAYLEN(szBufA), _TRUNCATE, "[%d]",
                  cVarDesc->elemdescVar.tdesc.lpadesc->rgbounds[i].cElements);
      WRITEANSI_AND_CHECK(fp, szBufA);
    }
  }
  else
  {
    cStrTempW.Empty();
    hRes = TypeDescToString(cStrTempW, &(cVarDesc->elemdescVar.tdesc), lpTypeInfo, FALSE);
    EXIT_ON_ERROR(hRes);
    WRITEWIDE_AND_CHECK(fp, (LPWSTR)cStrTempW);
    WRITEANSI_AND_CHECK(fp, " ");
    WRITEBSTR_AND_CHECK(fp, bstrMemberName);
  }
  WRITEANSI_AND_CHECK(fp, ";\r\n");
  return S_OK;
}
Beispiel #2
0
int _tmain(int argc, TCHAR* argv[])
{
	CSysInfo sysinfo;

	_tprintf_s(_T("%s 's version: "), sysinfo.GetModuleName().c_str());
	_tprintf_s(_T("%s,cc:"), sysinfo.GetAppVersionInfo().FileVersion.c_str());
	_tprintf_s(_T("%s"), sysinfo.GetAppVersionInfo().CompanyName.c_str());

	getchar();

	return 0;
}
void DoAtlCustomTraitsList()
{
   // Declare the array, with our data type and traits class 

   CAtlList < MyData, MyTraits > MyList;

   // Create some variables of our data type

   MyData add_item, search_item;

   // Add some elements to the list.

   add_item.ID = 1;
   _stprintf_s(add_item.name, _T("Rumpelstiltskin"));
   _stprintf_s(add_item.address, _T("One Grimm Way"));

   MyList.AddHead(add_item);

   add_item.ID = 2;
   _stprintf_s(add_item.name, _T("Rapunzel"));
   _stprintf_s(add_item.address, _T("One Grimm Way"));

   MyList.AddHead(add_item);

   add_item.ID = 3;
   _stprintf_s(add_item.name, _T("Cinderella"));
   _stprintf_s(add_item.address, _T("Two Grimm Way"));

   MyList.AddHead(add_item);

   // Create an element which will be used
   // to search the list for a match.

   search_item.ID = 2;
   _stprintf_s(search_item.name, _T("Don't care"));
   _stprintf_s(search_item.address, _T("Don't care"));

   // Perform a comparison by searching for a match
   // between any element in the list, and our
   // search item. This operation will use the
   // (overridden) comparison operator and will
   // find a match when the IDs are the same.

   POSITION i;

   i = MyList.Find(search_item);

   if (i != NULL)
      _tprintf_s(_T("Item found!\n"));
   else
      _tprintf_s(_T("Item not found.\n"));
}
void TestRequestAndReply(IIPCObject* pNamedPipeClient)
{
    IIPCConnectorIterator* pClientIterator = pNamedPipeClient->GetClients();

    while(FALSE == g_bExit)
    {
        for(pClientIterator->Begin(); !pClientIterator->End(); pClientIterator->Next())
        {
            IIPCConnector* aClient = pClientIterator->GetCurrent();

            if(NULL == aClient)
                continue;

            TCHAR* sRequest = _T("1+1=2\r\n");
            DWORD dwRequestSize = _tcslen(sRequest) * sizeof(TCHAR);
            DWORD dwTransSize = 0;

            TCHAR sReply[MAX_PATH] = {0};

            if(aClient->RequestAndReply(sRequest, dwRequestSize, sReply, MAX_PATH, &dwTransSize))
            {
                _tsetlocale(LC_ALL, _T("chs"));
                _tprintf_s(_T("%s"), sReply);
            }
        }
    }
}
    virtual void OnRequest(IIPCObject* pServer, IIPCConnector* pClient, LPCVOID lpBuf, DWORD dwBufSize)
    {
        if(NULL == lpBuf || dwBufSize == 0)
            return ;

        LPUSER_DATA_PACKAGE userRequest = (LPUSER_DATA_PACKAGE)lpBuf;
        _tsetlocale(LC_ALL, _T("chs"));
        _tprintf_s(_T("%s"), userRequest->lpBuf);


        if(userRequest->dwPackageType == 100)
        {
            TCHAR sReply[MAX_PATH] = {0};
            _stprintf_s(sReply, _T("同步应答:1+1=2 \r\n"));

            _USER_DATA_PACKAGE userRequest = {0};
            userRequest.dwPackageType = 100;
            _tcscpy_s(userRequest.lpBuf, MAX_PATH, sReply);

            pClient->PostMessage(&userRequest, sizeof(_USER_DATA_PACKAGE));
        }
        else
        {
            TCHAR sReply[MAX_PATH] = {0};
            _stprintf_s(sReply, _T("异步应答:你好,客户端 \r\n"));

            _USER_DATA_PACKAGE userRequest = {0};
            userRequest.dwPackageType = 1;
            _tcscpy_s(userRequest.lpBuf, MAX_PATH, sReply);

            pClient->PostMessage(&userRequest, sizeof(_USER_DATA_PACKAGE));
        }

    }
Beispiel #6
0
int _tmain(int argc, _TCHAR* argv[])
{
	DWORD dwThreadID[MAX_THREADS];
	HANDLE hThread[MAX_THREADS];

	while( 1 )
	{
		hThread[cntOfThread] =
			CreateThread(
			NULL ,					//디폴트 보안 속성 지정
			1024*1024 ,						//디폴트 스택사이즈
			ThreadProc ,			//쓰레드 함수
			( LPVOID )cntOfThread ,	//쓰레드 함수 전달인자
			0 ,						//디폴트 생성 flag 지정
			&dwThreadID[cntOfThread]//쓰레드ID 반환
			);

		if( hThread[cntOfThread] == NULL )
		{
			_tprintf_s(
				_T( "MAXIMUM THREAD NUMBER: %d \n" ) , 
				cntOfThread 
				);
			break;
		}
		cntOfThread++;
	}
	for( DWORD i = 0; i < cntOfThread; i++ )
	{
		CloseHandle( hThread[i] );
	}

	return 0;
}
Beispiel #7
0
void gcfosdb::PrintDBStats()
	{
	DB_BTREE_STAT	*stats = NULL;
	DB_QUEUE_STAT	*q_stat;
	DBTYPE			type;

	t->stat(NULL, &stats, DB_READ_UNCOMMITTED);

	if(stats == NULL)
		{
		_tprintf_s(TEXT("stat() call failed\n"));
		return;
		}
	t->get_type(&type);
	switch(type)
		{
		case DB_BTREE:
			_tprintf_s(L"Keys:%u,"
					   L"Page:%u(%u),"
					   L"Lvl:%u,"
					   L"Free:%u,"
					   L"Empty:%u,"
					   L"#Leaf:%u\n",
					   stats->bt_nkeys, stats->bt_pagecnt, stats->bt_pagesize, 
					   stats->bt_levels, stats->bt_free, stats->bt_empty_pg,
					   stats->bt_leaf_pg);
			break;
		case DB_QUEUE:
		case DB_RECNO:
			q_stat = (DB_QUEUE_STAT *)stats;
			_tprintf_s(L"Keys:%u,"
					   L"Page:%u(%u),"
					   L"Len:%u,"
					   L"Cur:%u,"
					   L"First:%u\n",
					   q_stat->qs_nkeys, q_stat->qs_pages, q_stat->qs_pagesize, 
					   q_stat->qs_re_len, q_stat->qs_cur_recno, q_stat->qs_first_recno );
			break;
		default:
			_tprintf_s(TEXT("PrintDBStats - unsupported db type\n"));
			break;
		}

	free(stats);

	return;
	}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
void ShutDown(IN RPC_BINDING_HANDLE hBinding)
{
    RPC_STATUS nStatus;

    // Tell the server to stop listening for remote procedure calls
    _tprintf_s(TEXT("Shutting down the server\n"));
    nStatus = RpcMgmtStopServerListening(NULL);
    EXIT_IF_FAIL(nStatus, "RpcMgmtStopServerListening");
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
void GetRemoteEnv(IN RPC_BINDING_HANDLE hBinding,
				  unsigned long *nNumLines,
				  str **psEnvironmentBlock)
{
    int nIdx = 0;       // Loop counter                                 
    TCHAR 
        *pcTemp,        // Temporary pointer to the environment block   
        *pcEnv;         // Pointer to the environment block             


    // Get pointer to environment block	
    pcEnv = (TCHAR *) GetEnvironmentStrings();

    // First count how many lines, must know how much memory to allocate
    *nNumLines  = 0;            // Initialize number of lines to 0      
    pcTemp = pcEnv;             // Set tempptr equal to envptr          
    while (*pcTemp != NULL_CHAR)
    {
        // Don't count the lines that starts with IGNORE_CHAR	        
        if(*pcTemp != IGNORE_CHAR)
        {
            (*nNumLines)++;     // Increase the number of lines     
        }

        // Increment the string pointer. Each line ends in \0, and  
        // \0\0 means end of block                                  
        pcTemp += (_tcslen(pcTemp) + 1);
    }

    // Allocate the memory needed for the line pointer 
    if(NULL == (*psEnvironmentBlock = (str *) 
        midl_user_allocate((*nNumLines) * sizeof(str))))
    {
        _tprintf_s(TEXT("REMOTE.C : Memory allocation error\n"));
        return;
    }

    // Iterate through all the environment strings, allocate memory,    
    // and copy them                                                    
    while (*pcEnv != NULL_CHAR)
    {
        // Don't count the lines that starts with IGNORE_CHAR
        if(*pcEnv != IGNORE_CHAR)
        {
            // Allocate the space needed for the strings 
            (*psEnvironmentBlock)[nIdx] = (str) midl_user_allocate(
                sizeof(TCHAR) * (_tcslen(pcEnv) + 1));
			
            // Copy the environment string to the allocated memory
            _tcscpy_s((*psEnvironmentBlock)[nIdx++],sizeof(TCHAR) * (_tcslen(pcEnv) + 1), pcEnv);
        }
        
        // Increment the string pointer. Each line ends in \0, and
        // \0\0 means end of block
        pcEnv += (_tcslen(pcEnv) + 1);
    }
}
Beispiel #10
0
int _tmain(int argc, _TCHAR* argv[])
{
  TNktComPtr<ITypeLib> cTypeLib;
  FILE *fp;
  HRESULT hRes;

  if (argc != 3)
  {
    _tprintf_s(_T("Use: Tlb2H input output-h-file.\n\n"));
    _tprintf_s(_T("Where 'input' can be a .TLB, .DLL or .OCX file or a registry GUID\n"));
    _tprintf_s(_T("  and 'output' is target header filename.\n"));
    return 1;
  }
  hRes = ::CoInitialize(0);
  if (FAILED(hRes))
  {
    _tprintf_s(_T("Error (%08X): Cannot initialize COM.\n"), (ULONG)hRes);
    return 1;
  }
  hRes = DoLoadTypeLib(&cTypeLib, argv[1]);
  if (FAILED(hRes))
  {
    ::CoUninitialize();
    _tprintf_s(_T("Error (%08X): Cannot load type library.\n"), (ULONG)hRes);
    return 1;
  }
  //write destinantion file
  if (_tfopen_s(&fp, argv[2], _T("wb")) != 0)
  {
    ::CoUninitialize();
    _tprintf_s(_T("Error: Cannot create destination file.\n"));
    return 1;
  }
  hRes = Process(fp, cTypeLib);
  fclose(fp);
  ::CoUninitialize();
  if (FAILED(hRes))
  {
    if (hRes == E_CANNOTWRITEFILE)
      _tprintf_s(_T("Error: Cannot write destination file.\n"));
    else
      _tprintf_s(_T("Error (%08X): Cannot process type library.\n"), (ULONG)hRes);
    return 1;
  }
  //done
  _tprintf_s(_T("Success!\n"));
  return 0;
}
Beispiel #11
0
DWORD WINAPI ThreadProc( LPVOID lpParam )
{
	DWORD threadNum = ( DWORD )lpParam;
	while( 1 )
	{
		_tprintf_s( _T( "thread num : %d \n" ) , threadNum );
		Sleep( 5000 );
	}
	return 0;
}
Beispiel #12
0
	void logging(TCHAR* logString, ...)
	{
		va_list ap;
		TCHAR szLog[1024] = { 0, };

		va_start(ap, logString);
		_vstprintf_s(szLog, logString, ap);
		va_end(ap);

		_tprintf_s(szLog);
	}
Beispiel #13
0
UINT64 gcfosdb::size()
	{
	DB_BTREE_STAT	*stats = NULL;
	UINT32			rtn = 0;
	
	if(t->stat(NULL, &stats, DB_FAST_STAT | DB_READ_UNCOMMITTED) != 0 || stats == NULL)
		{
		_tprintf_s(TEXT("gcfosdb::size - stat() call failed\n"));
		return 0;
		}

	rtn = stats->bt_nkeys;
	free(stats);
	return rtn;
	}
/*
 * Connect to the Tally over a specific port and get all the companies
 */
BOOL CTallyExporterDlg::GetCompanyListFromTallyServer(int port, CompanyListResponse& companyListResponseRef)
{
   CInternetSession session(_T("My Session"));
   CHttpConnection* pServer = NULL;
   CHttpFile* pFile = NULL;
   try
   {
      CString strServerName;
      DWORD dwRet = 0;
	  CString strParam = "<ENVELOPE><HEADER><TALLYREQUEST>Export Data</TALLYREQUEST></HEADER><BODY><EXPORTDATA><REQUESTDESC><REPORTNAME>List of Companies</REPORTNAME></REQUESTDESC></EXPORTDATA></BODY></ENVELOPE>";
	  CString strHeaders  = _T("Content-Type: application/x-www-form-urlencoded;Accept-Encoding: gzip,deflate");
	  CString acceptedTypes[] = {_T("text/html")};

      pServer = session.GetHttpConnection(_T("localhost"),NULL, port, NULL, NULL);
      pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_POST, _T(""), NULL,1,(LPCTSTR*)acceptedTypes,NULL,INTERNET_FLAG_EXISTING_CONNECT);

	  pFile->SendRequest(strHeaders, (LPVOID)(LPCTSTR)strParam, strParam.GetLength());
      pFile->QueryInfoStatusCode(dwRet);

      if (dwRet == HTTP_STATUS_OK)
      {
         CHAR szBuff[1024];
         while (pFile->Read(szBuff, 1024) > 0)
         {
            printf_s("%1023s", szBuff);
         }
		 GetCompanyListFromCSVResponse(companyListResponseRef, szBuff);
      }
	  else
	  { 
		  //Do something as server is not sending response as expected.
	  }
      delete pFile;
      delete pServer;
   }
   catch (CInternetException* pEx)
   {
       //catch errors from WinInet
      TCHAR pszError[64];
      pEx->GetErrorMessage(pszError, 64);
      _tprintf_s(_T("%63s"), pszError);
   }
   session.Close();
   return false;
}
/* ===================================================================
*         GET Tally TB Response for a given request
*  ===================================================================
*/
BOOL CTallyExporterDlg::GetTallyTBResponse(CString& xmlTBRequestRef,vector<string>& allRowsOfTBRef, int port)
{
   CInternetSession session(_T("TB Session"));
   CHttpConnection* pServer = NULL;
   CHttpFile* pFile = NULL;   

   try
   {
      CString strServerName;
      DWORD dwRet = 0;
	  CString strHeaders  = _T("Content-Type: application/x-www-form-urlencoded;Accept-Encoding: gzip,deflate");
	  CString acceptedTypes[] = {_T("text/html")};

      pServer = session.GetHttpConnection(_T("localhost"),NULL, port, NULL, NULL);
      pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_POST, _T(""), NULL,1,(LPCTSTR*)acceptedTypes,NULL,INTERNET_FLAG_EXISTING_CONNECT);

	  pFile->SendRequest(strHeaders, (LPVOID)(LPCTSTR)xmlTBRequestRef, xmlTBRequestRef.GetLength());
      pFile->QueryInfoStatusCode(dwRet);

	  CString csvLinesToBeRead;
	  CString& csvLinesToBeReadRef = csvLinesToBeRead;
      if (dwRet == HTTP_STATUS_OK)
      {
         while (pFile->ReadString(csvLinesToBeReadRef) == TRUE)
         {			 
			 allRowsOfTBRef.push_back((LPCTSTR)csvLinesToBeReadRef);
         }
      }
	  else
	  { 
		  //Do something as server is not sending response as expected.
	  }
      delete pFile;
      delete pServer;
   }
   catch (CInternetException* pEx)
   {
       //catch errors from WinInet
      TCHAR pszError[64];
      pEx->GetErrorMessage(pszError, 64);
      _tprintf_s(_T("%63s"), pszError);
   }
   session.Close();
   return false;
}
Beispiel #16
0
/*
 * Class:     com_Revsoft_Wabbitemu_CalcInterface
 * Method:    SaveCalcState
 * Signature: (Ljava/lang/String;)V
 */
JNIEXPORT jboolean JNICALL Java_com_Revsoft_Wabbitemu_calc_CalcInterface_SaveCalcState
		(JNIEnv *env, jclass classObj, jstring filePath) {
	checkThread();
	const char *path = env->GetStringUTFChars(filePath, JNI_FALSE);

    SAVESTATE_t *save;
    try {
        save = SaveSlot(lpCalc, "Wabbitemu", "Automatic save state");
    } catch (std::exception &e) {
        _tprintf_s(_T("Exception loading save state: %s"), e.what());
        return FALSE;
    }
	if (save != NULL) {
		WriteSave(path, save, ZLIB_CMP);
		FreeSave(save);
	}

	return (jboolean) (save != NULL);
}
Beispiel #17
0
int _tmain(int argc, _TCHAR* argv[])
{
	//1.파일 핸들 생성
	
	HANDLE hFile =
		CreateFile(
		_T( "data.dat" ) , GENERIC_READ | GENERIC_WRITE , 0 , NULL ,
		OPEN_EXISTING , FILE_ATTRIBUTE_NORMAL , NULL );
	if( hFile == INVALID_HANDLE_VALUE )
		_tprintf_s( _T( "Could not open file.\n" ) );
	


	//2.파일 오브젝트 생성

	HANDLE hMapFile =
		CreateFileMapping( 
		hFile , NULL , PAGE_WRITECOPY , 
		0 ,	1024 * 10 ,	NULL );				//파일 연결 최대 메모리 크기
	if( !hMapFile )
		_tprintf_s( _T( "Could not create map of file.\n" ) );


	//3.메모리에 연결

	int* pWrite =
		( int* )MapViewOfFile( hMapFile , FILE_MAP_COPY , 0 , 0 , 0 );
	if( !pWrite )
		_tprintf_s( _T( "Could not map view of file!\n" ) );

	//4.Do Something

	pWrite[0] = 1 , pWrite[1] = 3 , pWrite[2] = 0;
	pWrite[3] = 2 , pWrite[4] = 4 , pWrite[5] = 5;
	pWrite[6] = 8 , pWrite[7] = 6 , pWrite[8] = 7;

	//SortIntData( pWrite , 9 );
	for( int i = 0; i < 9; ++i )
	{
		_tprintf_s( _T( "%3d" ) , pWrite[i] );
	}
	_tprintf_s( _T( "\n" ) );
	UnmapViewOfFile( pWrite );
	CloseHandle( hMapFile );

	CloseHandle( hFile );
	_tprintf_s( _T( "End of process!\n" ) );
	return 0;
}
Beispiel #18
0
int _tmain(int argc, TCHAR* argv[])
{
	int a, b;

	_try
	{
		_tprintf_s(_T("input divide string [ a / b ] : "));
		//_tscanf(_T("%d %d"), &a, &b);
		_tscanf_s(_T("%d %d"), &a, &b);
		
		if (b == 0)
			return -1;
	}
	_finally
	{
		_tprintf(_T("_finally block!\n"));
	}

	_tprintf(_T("result: %d\n"), a / b);
	return 0;
}
Beispiel #19
0
void COSError::LogMessage(const TCHAR* msg)
{
	static CLock lock;
	TCHAR txt[512];
	size_t len = CTimeWrap::GetNow(txt, _countof(txt));
	_stprintf_s(txt + len, _countof(txt) - len, _T("  %s%s"), msg, _T("\r\n"));
	lock.Lock();
	try
	{
		if(m_proc!=NULL)
			m_proc(txt);
		 else if(m_show_out)
			 _tprintf_s(_T("%s"), txt);

		if(m_log != NULL)
			_fputts(txt, m_log);
	}
	catch(...)
	{
	}
	lock.UnLock();
}
Beispiel #20
0
int _tmain(int argc, _TCHAR* argv[])
{
	HANDLE hTimer = NULL;
	LARGE_INTEGER liDueTime;

	liDueTime.QuadPart = -10000000; 

	hTimer = CreateWaitableTimer( NULL , FALSE , _T( "WaitableTimer" ) );
	if( !hTimer )
	{
		return 1;
	}

	_tprintf_s( _T( "Waiting for 10 second...\n" ) );
	SetWaitableTimer( hTimer , &liDueTime , 5000 ,
					  TimerAPCProc , _T( "Timer was signaled\n"), FALSE);

	while( 1 )
		SleepEx( INFINITE , TRUE );

	return 0;
}
Beispiel #21
0
static HRESULT ProcessFunction(__in FILE *fp, __in WORD nIndex, __in TYPEATTR* lpTypeAttr,
                               __in ITypeInfo *lpTypeInfo, __in SIZE_T nIndent, __in LPWSTR szParentThisW)
{
  CAutoFuncDesc cFuncDesc;
  CNktStringW cStrTempW;
  CNktComBStr bstrNames[MAX_FUNCTION_NAMES];
  BSTR bstr[MAX_FUNCTION_NAMES];
  HRESULT hRes;
  CNktComVariant vtValue;
  UINT i, j, nNamesCount;
  char szBufA[32];

  hRes = cFuncDesc.Set(lpTypeInfo, nIndex);
  EXIT_ON_ERROR(hRes);
  //Write return type
  cStrTempW.Empty();
  hRes = TypeDescToString(cStrTempW, &(cFuncDesc->elemdescFunc.tdesc), lpTypeInfo, FALSE);
  EXIT_ON_ERROR(hRes);
  WRITEINDENT_AND_CHECK(fp, nIndent);
  WRITEWIDE_AND_CHECK(fp, (LPWSTR)cStrTempW);
  WRITEANSI_AND_CHECK(fp, " (");
  if (lpTypeAttr->typekind != TKIND_DISPATCH)
  {
    // Write calling convention
    switch (cFuncDesc->callconv)
    {
      case CC_CDECL:
        WRITEANSI_AND_CHECK(fp, "_cdecl ");
        break;
      case CC_PASCAL:
        WRITEANSI_AND_CHECK(fp, "__pascal ");
        break;
      case CC_STDCALL:
        WRITEANSI_AND_CHECK(fp, "__stdcall ");
        break;
      default:
        _tprintf_s(_T("Error: Unsupported calling convetion '%04X'.\n"), cFuncDesc->callconv);
        return E_NOTIMPL;
    }
  }
  else
  {
    WRITEANSI_AND_CHECK(fp, "__stdcall ");
  }
  WRITEANSI_AND_CHECK(fp, "*");
  // Write methodname
  //
  // Problem:  If a property has the propput or propputref attributes the
  // 'right hand side' (rhs) is *always* the last parameter and MkTypeLib
  // strips the parameter name.  Thus you will always get 1 less name
  // back from ::GetNames than normal.
  //
  // Thus for the example below
  //  [propput] void Color([in] VARIANT rgb, [in] VARIANT rgb2 );
  // without taking this into consderation the output would be
  //  [propput] void Color([in] VARIANT rgb, [in] VARIANT );
  // when it should be
  //  [propput] void Color([in] VARIANT rgb, [in] VARIANT rhs );
  //
  // Another weirdness comes from a bug (which will never be fixed)
  // where optional parameters on property functions were allowed.
  // Because they were allowed by accident people used them, so they
  // are still allowed.
  nNamesCount = 0;
  hRes = lpTypeInfo->GetNames(cFuncDesc->memid, bstr, MAX_FUNCTION_NAMES, &nNamesCount);
  EXIT_ON_ERROR(hRes);
  for (i=0; i<nNamesCount; i++)
    bstrNames[i].Attach(bstr[i]);
  // fix for 'rhs' problem
  if (nNamesCount < (UINT)cFuncDesc->cParams+1)
  {
    hRes = bstrNames[nNamesCount++].Set(L"rhs");
    EXIT_ON_ERROR(hRes);
  }
  NKT_ASSERT(nNamesCount == cFuncDesc->cParams+1);
  if ((cFuncDesc->invkind & INVOKE_PROPERTYGET) != 0)
  {
    WRITEANSI_AND_CHECK(fp, "get_");
  }
  else if ((cFuncDesc->invkind & INVOKE_PROPERTYPUT) != 0)
  {
    WRITEANSI_AND_CHECK(fp, "put_");
  }
  else if ((cFuncDesc->invkind & INVOKE_PROPERTYPUTREF) != 0)
  {
    WRITEANSI_AND_CHECK(fp, "putref_");
  }
  WRITEBSTR_AND_CHECK(fp, bstrNames[0]);
  WRITEANSI_AND_CHECK(fp, ")(");
  if (szParentThisW != NULL)
  {
    WRITEWIDE_AND_CHECK(fp, szParentThisW);
    WRITEANSI_AND_CHECK(fp, "* This");
  }
  // params have the format
  //   [attributes] type paramname
  // where attributes can be
  //   in, out, optional, string   (string is not valid for TKIND_MODULE)
  for (i=0; i<(UINT)(cFuncDesc->cParams); i++)
  {
    if (i > 0 || szParentThisW != NULL)
    {
      WRITEANSI_AND_CHECK(fp, ", ");
    }
    // type
    if ((cFuncDesc->lprgelemdescParam[i].tdesc.vt & 0x0FFF) == VT_CARRAY)
    {
      // type name[n]
      cStrTempW.Empty();
      hRes = TypeDescToString(cStrTempW, &(cFuncDesc->lprgelemdescParam[i].tdesc.lpadesc->tdescElem),
                              lpTypeInfo, FALSE);
      EXIT_ON_ERROR(hRes);
      WRITEWIDE_AND_CHECK(fp, (LPWSTR)cStrTempW);
      WRITEANSI_AND_CHECK(fp, " ");
      WRITEBSTR_AND_CHECK(fp, bstrNames[i+1]);
      for (j=0; j<cFuncDesc->lprgelemdescParam[i].tdesc.lpadesc->cDims; j++)
      {
        _snprintf_s(szBufA, X_ARRAYLEN(szBufA), _TRUNCATE, "[%d]",
                    cFuncDesc->lprgelemdescParam[i].tdesc.lpadesc->rgbounds[j].cElements);
        WRITEANSI_AND_CHECK(fp, szBufA);
      }
    }
    else
    {
      cStrTempW.Empty();
      hRes = TypeDescToString(cStrTempW, &(cFuncDesc->lprgelemdescParam[i].tdesc), lpTypeInfo, FALSE);
      EXIT_ON_ERROR(hRes);
      WRITEWIDE_AND_CHECK(fp, (LPWSTR)cStrTempW);
      WRITEANSI_AND_CHECK(fp, " ");
      WRITEBSTR_AND_CHECK(fp, bstrNames[i+1]);
    }
  }
  WRITEANSI_AND_CHECK(fp, ");\r\n");
  return S_OK;
}
Beispiel #22
0
int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPTSTR lpstrCmdLine, int nCmdShow)
{
	// Define CrashRpt configuration parameters
	CR_INSTALL_INFO info;  
	memset(&info, 0, sizeof(CR_INSTALL_INFO));  
	info.cb = sizeof(CR_INSTALL_INFO);    
	info.pszAppName = _T("crashtestdummy");
	info.pszAppVersion = _T("1.0.0");  
	info.pszEmailSubject = _T("Error Report");  
	info.pszEmailTo = _T("*****@*****.**");
	info.uPriorities[CR_HTTP] = 3;  // First try send report over HTTP 
	info.uPriorities[CR_SMTP] = 2;  // Second try send report over SMTP  
	info.uPriorities[CR_SMAPI] = 1; // Third try send report over Simple MAPI    
	// Install all available exception handlers
	info.dwFlags |= CR_INST_ALL_POSSIBLE_HANDLERS;
	// Restart the app on crash 
	info.dwFlags |= CR_INST_APP_RESTART; 
	info.dwFlags |= CR_INST_SEND_QUEUED_REPORTS; 
	info.pszRestartCmdLine = _T("/restart");
	// Define the Privacy Policy URL 
	info.pszPrivacyPolicyURL = _T("http://myapp.com/privacypolicy.html"); 

	// Install crash reporting
	int nResult = crInstall(&info);    
	if(nResult!=0)  
	{    
		// Something goes wrong. Get error message.
		TCHAR szErrorMsg[512] = _T("");        
		crGetLastErrorMsg(szErrorMsg, 512);    
		_tprintf_s(_T("%s\n"), szErrorMsg);    
		return 1;
	} 

	// Set crash callback function
	crSetCrashCallback(CrashCallback, NULL);

	// Add our log file to the error report
	crAddFile2(_T("log.txt"), NULL, _T("Log File"), CR_AF_MAKE_FILE_COPY);    

	// We want the screenshot of the entire desktop is to be added on crash
	crAddScreenshot2(CR_AS_VIRTUAL_SCREEN, 0);   

	// Add a named property that means what graphics adapter is
	// installed on user's machine
	crAddProperty(_T("VideoCard"), _T("nVidia GeForce 8600 GTS"));







	HRESULT hRes = ::CoInitialize(NULL);
	// If you are running on NT 4.0 or higher you can use the following call instead to 
	// make the EXE free threaded. This means that calls come in on a random RPC thread.
	//	HRESULT hRes = ::CoInitializeEx(NULL, COINIT_MULTITHREADED);
	ATLASSERT(SUCCEEDED(hRes));

	// this resolves ATL window thunking problem when Microsoft Layer for Unicode (MSLU) is used
	::DefWindowProc(NULL, 0, 0, 0L);

	AtlInitCommonControls(ICC_BAR_CLASSES);	// add flags to support other controls

	hRes = _Module.Init(NULL, hInstance);
	ATLASSERT(SUCCEEDED(hRes));

	int nRet = Run(lpstrCmdLine, nCmdShow);

	_Module.Term();
	::CoUninitialize();






	errno_t err = _tfopen_s(&g_hLog, _T("log.txt"), _T("wt"));
  if(err!=0 || g_hLog==NULL)
  {
    _tprintf_s(_T("Error opening log.txt\n"));
    return 1; // Couldn't open log file
  }

  log_write(_T("Started successfully\n"));

  
  // There is a hidden error in the main() function
  // Call of _tprintf_s with NULL parameter
  TCHAR* szFormatString = NULL;
  _tprintf_s(szFormatString);


  // Close the log file
  if(g_hLog!=NULL)
  {
    fclose(g_hLog);
    g_hLog = NULL;// Clean up handle
  }

  // Uninitialize CrashRpt before exiting the main function
  crUninstall();






	return nRet;
}
Beispiel #23
0
// WinMain parses the command line and either calls the main App
// routine or, under NT, the main service routine.
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
{

	if (VNCOS.OS_NOTSUPPORTED==true)
	{
		 MessageBoxSecure(NULL, "Error OS not supported","Unsupported OS", MB_ICONERROR);
		return true;
	}
	// make vnc last service to stop
	SetProcessShutdownParameters(0x100,false);
	// handle dpi on aero
	/*HMODULE hUser32 = LoadLibrary(_T("user32.dll"));
	typedef BOOL (*SetProcessDPIAwareFunc)();
	SetProcessDPIAwareFunc setDPIAware=NULL;
	if (hUser32) setDPIAware = (SetProcessDPIAwareFunc)GetProcAddress(hUser32, "SetProcessDPIAware");
	if (setDPIAware) setDPIAware();
	if (hUser32) FreeLibrary(hUser32);*/

#ifdef IPP
	InitIpp();
#endif
#ifdef CRASHRPT
	CR_INSTALL_INFO info;
	memset(&info, 0, sizeof(CR_INSTALL_INFO));
	info.cb = sizeof(CR_INSTALL_INFO);
	info.pszAppName = _T("UVNC");
	info.pszAppVersion = _T("1.2.0.9");
	info.pszEmailSubject = _T("UVNC server 1.2.0.9 Error Report");
	info.pszEmailTo = _T("*****@*****.**");
	info.uPriorities[CR_SMAPI] = 1; // Third try send report over Simple MAPI    
	// Install all available exception handlers
	info.dwFlags |= CR_INST_ALL_POSSIBLE_HANDLERS;
	// Restart the app on crash 
	info.dwFlags |= CR_INST_APP_RESTART;
	info.dwFlags |= CR_INST_SEND_QUEUED_REPORTS;
	info.dwFlags |= CR_INST_AUTO_THREAD_HANDLERS;
	info.pszRestartCmdLine = _T("/restart");
	// Define the Privacy Policy URL 

	// Install crash reporting
	int nResult = crInstall(&info);
	if (nResult != 0)
	{
		// Something goes wrong. Get error message.
		TCHAR szErrorMsg[512] = _T("");
		crGetLastErrorMsg(szErrorMsg, 512);
		_tprintf_s(_T("%s\n"), szErrorMsg);
		return 1;
	}
#endif
	bool Injected_autoreconnect=false;
	SPECIAL_SC_EXIT=false;
	SPECIAL_SC_PROMPT=false;
	setbuf(stderr, 0);

	// [v1.0.2-jp1 fix] Load resouce from dll
	hInstResDLL = NULL;

	 //limit the vnclang.dll searchpath to avoid
	char szCurrentDir[MAX_PATH];
	char szCurrentDir_vnclangdll[MAX_PATH];
	if (GetModuleFileName(NULL, szCurrentDir, MAX_PATH))
	{
		char* p = strrchr(szCurrentDir, '\\');
		*p = '\0';
	}
	strcpy (szCurrentDir_vnclangdll,szCurrentDir);
	strcat (szCurrentDir_vnclangdll,"\\");
	strcat (szCurrentDir_vnclangdll,"vnclang_server.dll");

	hInstResDLL = LoadLibrary(szCurrentDir_vnclangdll);

	if (hInstResDLL == NULL)
	{
		hInstResDLL = hInstance;
	}
//	RegisterLinkLabel(hInstResDLL);

    //Load all messages from ressource file
    Load_Localization(hInstResDLL) ;

	char WORKDIR[MAX_PATH];
	if (GetModuleFileName(NULL, WORKDIR, MAX_PATH))
		{
		char* p = strrchr(WORKDIR, '\\');
		if (p == NULL) return 0;
		*p = '\0';
		}
    char progname[MAX_PATH];
    strncpy(progname, WORKDIR, sizeof progname);
    progname[MAX_PATH - 1] = 0;
	//strcat(WORKDIR,"\\");
	//strcat(WORKDIR,"WinVNC.log");

	vnclog.SetFile();
	//vnclog.SetMode(4);
	//vnclog.SetLevel(10);

#ifdef _DEBUG
	{
		// Get current flag
		int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );

		// Turn on leak-checking bit
		tmpFlag |= _CRTDBG_LEAK_CHECK_DF;

		// Set flag to the new value
		_CrtSetDbgFlag( tmpFlag );
	}
#endif

	// Save the application instance and main thread id
	hAppInstance = hInstance;
	mainthreadId = GetCurrentThreadId();

	// Initialise the VSocket system
	VSocketSystem socksys;
	if (!socksys.Initialised())
	{
		MessageBoxSecure(NULL, sz_ID_FAILED_INIT, szAppName, MB_OK);
#ifdef CRASHRPT
		crUninstall();
#endif
		return 0;
	}
    // look up the current service name in the registry.
    GetServiceName(progname, service_name);

	// Make the command-line lowercase and parse it
	size_t i;
	for (i = 0; i < strlen(szCmdLine); i++)
	{
		szCmdLine[i] = tolower(szCmdLine[i]);
	}
	BOOL argfound = FALSE;
	for (i = 0; i < strlen(szCmdLine); i++)
	{
		if (szCmdLine[i] <= ' ')
			continue;
		argfound = TRUE;

		if (strncmp(&szCmdLine[i], winvncSettingshelper, strlen(winvncSettingshelper)) == 0)
		{
			Sleep(3000);
			char mycommand[MAX_PATH];
			i+=strlen(winvncSettingshelper);
			strcpy( mycommand, &(szCmdLine[i+1]));
			Set_settings_as_admin(mycommand);
#ifdef CRASHRPT
			crUninstall();
#endif
			return 0;
		}

		if (strncmp(&szCmdLine[i], winvncStopserviceHelper, strlen(winvncStopserviceHelper)) == 0)
		{
			Sleep(3000);
			Set_stop_service_as_admin();
#ifdef CRASHRPT
			crUninstall();
#endif
			return 0;
		}

		if (strncmp(&szCmdLine[i], winvncKill, strlen(winvncKill)) == 0)
		{
			static HANDLE		hShutdownEventTmp;
			hShutdownEventTmp = OpenEvent(EVENT_ALL_ACCESS, FALSE, "Global\\SessionEventUltra");
			SetEvent(hShutdownEventTmp);
			CloseHandle(hShutdownEventTmp);

			//adzm 2010-02-10 - Finds the appropriate VNC window for any process. Sends this message to all of them!
			// do removed, loops forever with cpu 100
			HWND hservwnd = NULL;
			hservwnd = FindWinVNCWindow(false);
				if (hservwnd!=NULL)
				{
					PostMessage(hservwnd, WM_COMMAND, 40002, 0);
					PostMessage(hservwnd, WM_CLOSE, 0, 0);
				}
#ifdef CRASHRPT
				crUninstall();
#endif
			return 0;
		}

		if (strncmp(&szCmdLine[i], winvncopenhomepage, strlen(winvncopenhomepage)) == 0)
		{
			Open_homepage();
#ifdef CRASHRPT
			crUninstall();
#endif
			return 0;
		}

		if (strncmp(&szCmdLine[i], winvncopenforum, strlen(winvncopenforum)) == 0)
		{
			Open_forum();
#ifdef CRASHRPT
			crUninstall();
#endif
			return 0;
		}

		if (strncmp(&szCmdLine[i], winvncStartserviceHelper, strlen(winvncStartserviceHelper)) == 0)
		{
			Sleep(3000);
			Set_start_service_as_admin();
#ifdef CRASHRPT
			crUninstall();
#endif
			return 0;
		}

		if (strncmp(&szCmdLine[i], winvncInstallServiceHelper, strlen(winvncInstallServiceHelper)) == 0)
			{
				//Sleeps are realy needed, else runas fails...
				Sleep(3000);
				Set_install_service_as_admin();
#ifdef CRASHRPT
				crUninstall();
#endif
				return 0;
			}
		if (strncmp(&szCmdLine[i], winvncUnInstallServiceHelper, strlen(winvncUnInstallServiceHelper)) == 0)
			{
				Sleep(3000);
				Set_uninstall_service_as_admin();
#ifdef CRASHRPT
				crUninstall();
#endif
				return 0;
			}
		if (strncmp(&szCmdLine[i], winvncSoftwarecadHelper, strlen(winvncSoftwarecadHelper)) == 0)
			{
				Sleep(3000);
				Enable_softwareCAD_elevated();
#ifdef CRASHRPT
				crUninstall();
#endif
				return 0;
			}		 
		if (strncmp(&szCmdLine[i], winvncdelSoftwarecadHelper, strlen(winvncdelSoftwarecadHelper)) == 0)
			{
				Sleep(3000);
				delete_softwareCAD_elevated();
#ifdef CRASHRPT
				crUninstall();
#endif
				return 0;
			}
		if (strncmp(&szCmdLine[i], winvncRebootSafeHelper, strlen(winvncRebootSafeHelper)) == 0)
			{
				Sleep(3000);
				Reboot_in_safemode_elevated();
#ifdef CRASHRPT
				crUninstall();
#endif
				return 0;
			}

		if (strncmp(&szCmdLine[i], winvncRebootForceHelper, strlen(winvncRebootForceHelper)) == 0)
			{
				Sleep(3000);
				Reboot_with_force_reboot_elevated();
#ifdef CRASHRPT
				crUninstall();
#endif
				return 0;
			}

		if (strncmp(&szCmdLine[i], winvncSecurityEditorHelper, strlen(winvncSecurityEditorHelper)) == 0)
			{
				Sleep(3000);
				winvncSecurityEditorHelper_as_admin();
#ifdef CRASHRPT
				crUninstall();
#endif
				return 0;
			}
		if (strncmp(&szCmdLine[i], winvncSecurityEditor, strlen(winvncSecurityEditor)) == 0)
			{
			    typedef void (*vncEditSecurityFn) (HWND hwnd, HINSTANCE hInstance);
				vncEditSecurityFn vncEditSecurity = 0;
				char szCurrentDirl[MAX_PATH];
					if (GetModuleFileName(NULL, szCurrentDirl, MAX_PATH)) {
						char* p = strrchr(szCurrentDirl, '\\');
						*p = '\0';
						strcat (szCurrentDirl,"\\authSSP.dll");
					}
					HMODULE hModule = LoadLibrary(szCurrentDirl);
					if (hModule) {
						vncEditSecurity = (vncEditSecurityFn) GetProcAddress(hModule, "vncEditSecurity");
						HRESULT hr = CoInitialize(NULL);
						vncEditSecurity(NULL, hAppInstance);
						CoUninitialize();
						FreeLibrary(hModule);
					}
#ifdef CRASHRPT
					crUninstall();
#endif
				return 0;
			}

		if (strncmp(&szCmdLine[i], winvncSettings, strlen(winvncSettings)) == 0)
		{
			char mycommand[MAX_PATH];
			i+=strlen(winvncSettings);
			strcpy( mycommand, &(szCmdLine[i+1]));
			Real_settings(mycommand);
#ifdef CRASHRPT
			crUninstall();
#endif
			return 0;
		}
		
		if (strncmp(&szCmdLine[i], dsmpluginhelper, strlen(dsmpluginhelper)) == 0)
		{
			char mycommand[MAX_PATH];
			i += strlen(dsmpluginhelper);
			strcpy(mycommand, &(szCmdLine[i + 1]));
			Secure_Plugin_elevated(mycommand);
#ifdef CRASHRPT
			crUninstall();
#endif
			return 0;
		}

		if (strncmp(&szCmdLine[i], dsmplugininstance, strlen(dsmplugininstance)) == 0)
		{
			char mycommand[MAX_PATH];
			i += strlen(dsmplugininstance);
			strcpy(mycommand, &(szCmdLine[i + 1]));
			Secure_Plugin(mycommand);
#ifdef CRASHRPT
			crUninstall();
#endif
			return 0;
		}


		if (strncmp(&szCmdLine[i], winvncSoftwarecad, strlen(winvncSoftwarecad)) == 0)
		{
			Enable_softwareCAD();
#ifdef CRASHRPT
			crUninstall();
#endif
			return 0;
		}

		if (strncmp(&szCmdLine[i], winvncdelSoftwarecad, strlen(winvncdelSoftwarecad)) == 0)
		{
			delete_softwareCAD();
#ifdef CRASHRPT
			crUninstall();
#endif
			return 0;
		}

		if (strncmp(&szCmdLine[i], winvncRebootSafe, strlen(winvncRebootSafe)) == 0)
		{
			Reboot_in_safemode();
#ifdef CRASHRPT
			crUninstall();
#endif
			return 0;
		}

		if (strncmp(&szCmdLine[i], winvncRebootForce, strlen(winvncRebootForce)) == 0)
		{
			Reboot_with_force_reboot();
#ifdef CRASHRPT
			crUninstall();
#endif
			return 0;
		}

		if (strncmp(&szCmdLine[i], winvncStopservice, strlen(winvncStopservice)) == 0)
		{
			Real_stop_service();
#ifdef CRASHRPT
			crUninstall();
#endif
			return 0;
		}

		if (strncmp(&szCmdLine[i], winvncStartservice, strlen(winvncStartservice)) == 0)
		{
			Real_start_service();
#ifdef CRASHRPT
			crUninstall();
#endif
			return 0;
		}

		if (strncmp(&szCmdLine[i], winvncInstallService, strlen(winvncInstallService)) == 0)
			{
                // rest of command line service name, if provided.
                char *pServiceName = &szCmdLine[i];
                // skip over command switch, find next whitepace
                while (*pServiceName && !isspace(*(unsigned char*)pServiceName))
                    ++pServiceName;

                // skip past whitespace to service name
                while (*pServiceName && isspace(*(unsigned char*)pServiceName))
                    ++pServiceName;

                // strip off any quotes
                if (*pServiceName && *pServiceName == '\"')
                    ++pServiceName;

                if (*pServiceName)
                {
                    // look for trailing quote, if found, terminate the string there.
                    char *pQuote = pServiceName;
                    pQuote = strrchr(pServiceName, '\"');
                    if (pQuote)
                        *pQuote = 0;
                }
                // if a service name is supplied, and it differs except in case from
                // the default, use the supplied service name instead
                if (*pServiceName && (_strcmpi(pServiceName, service_name) != 0))
                {
                    strncpy(service_name, pServiceName, 256);
                    service_name[255] = 0;
                }
				install_service();
				Sleep(2000);
				char command[MAX_PATH + 32]; // 29 January 2008 jdp
                _snprintf(command, sizeof command, "net start \"%s\"", service_name);
				WinExec(command,SW_HIDE);
#ifdef CRASHRPT
				crUninstall();
#endif
				return 0;
			}
		if (strncmp(&szCmdLine[i], winvncUnInstallService, strlen(winvncUnInstallService)) == 0)
			{
				char command[MAX_PATH + 32]; // 29 January 2008 jdp
                // rest of command line service name, if provided.
                char *pServiceName = &szCmdLine[i];
                // skip over command switch, find next whitepace
                while (*pServiceName && !isspace(*(unsigned char*)pServiceName))
                    ++pServiceName;

                // skip past whitespace to service name
                while (*pServiceName && isspace(*(unsigned char*)pServiceName))
                    ++pServiceName;

                // strip off any quotes
                if (*pServiceName && *pServiceName == '\"')
                    ++pServiceName;

                if (*pServiceName)
                {
                    // look for trailing quote, if found, terminate the string there.
                    char *pQuote = pServiceName;
                    pQuote = strrchr(pServiceName, '\"');
                    if (pQuote)
                        *pQuote = 0;
                }

                if (*pServiceName && (_strcmpi(pServiceName, service_name) != 0))
                {
                    strncpy(service_name, pServiceName, 256);
                    service_name[255] = 0;
                }
                _snprintf(command, sizeof command, "net stop \"%s\"", service_name);
				WinExec(command,SW_HIDE);
				uninstall_service();
#ifdef CRASHRPT
				crUninstall();
#endif
				return 0;
			}

		if (strncmp(&szCmdLine[i], winvncRunService, strlen(winvncRunService)) == 0)
		{
			//Run as service
			if (!Myinit(hInstance)) return 0;
			fRunningFromExternalService = true;
			vncService::RunningFromExternalService(true);
			int returnvalue = WinVNCAppMain();
#ifdef CRASHRPT
			crUninstall();
#endif
			return returnvalue;
		}

		if (strncmp(&szCmdLine[i], winvncStartService, strlen(winvncStartService)) == 0)
		{
		start_service(szCmdLine);
#ifdef CRASHRPT
		crUninstall();
#endif
		return 0;
		}

		if (strncmp(&szCmdLine[i], winvncRunAsUserApp, strlen(winvncRunAsUserApp)) == 0)
		{
			// WinVNC is being run as a user-level program
			if (!Myinit(hInstance)) return 0;
			int returnvalue = WinVNCAppMain();
#ifdef CRASHRPT
			crUninstall();
#endif
			return returnvalue;
		}

		if (strncmp(&szCmdLine[i], winvncSCexit, strlen(winvncSCexit)) == 0)
		{
			SPECIAL_SC_EXIT=true;
			i+=strlen(winvncSCexit);
			continue;
		}

		if (strncmp(&szCmdLine[i], winvncSCprompt, strlen(winvncSCprompt)) == 0)
		{
			SPECIAL_SC_PROMPT=true;
			i+=strlen(winvncSCprompt);
			continue;
		}

		if (strncmp(&szCmdLine[i], winvncmulti, strlen(winvncmulti)) == 0)
		{
			multi=true;
			i+=strlen(winvncmulti);
			continue;
		}

		if (strncmp(&szCmdLine[i], winvnchttp, strlen(winvnchttp)) == 0)
		{
			G_HTTP=true;
			i+=strlen(winvnchttp);
			continue;
		}

		if (strncmp(&szCmdLine[i], winvncStopReconnect, strlen(winvncStopReconnect)) == 0)
		{
			i+=strlen(winvncStopReconnect);
			vncService::PostAddStopConnectClientAll();
			continue;
		}

		if (strncmp(&szCmdLine[i], winvncAutoReconnect, strlen(winvncAutoReconnect)) == 0)
		{
			// Note that this "autoreconnect" param MUST be BEFORE the "connect" one
			// on the command line !
			// wa@2005 -- added support for the AutoReconnectId
			i+=strlen(winvncAutoReconnect);
			Injected_autoreconnect=true;
			int start, end;
			char* pszId = NULL;
			start = i;
			// skip any spaces and grab the parameter
			while (szCmdLine[start] <= ' ' && szCmdLine[start] != 0) start++;

			if ( strncmp( &szCmdLine[start], winvncAutoReconnectId, strlen(winvncAutoReconnectId) ) == 0 )
			{
				end = start;
				while (szCmdLine[end] > ' ') end++;

				if (end - start > 0)
				{

					pszId = new char[end - start + 1];

					strncpy(pszId, &(szCmdLine[start]), end - start);
					pszId[end - start] = 0;
					pszId = _strupr(pszId);
				}
//multiple spaces between autoreconnect and id
				i = end;
			}// end of condition we found the ID: parameter

			// NOTE:  id must be NULL or the ID:???? (pointer will get deleted when message is processed)
			// We can not contact a runnning service, permissions, so we must store the settings
			// and process until the vncmenu has been started

			if (!vncService::PostAddAutoConnectClient( pszId ))
			{
				PostAddAutoConnectClient_bool=true;
				if (pszId==NULL)
				{
					PostAddAutoConnectClient_bool_null=true;
					PostAddAutoConnectClient_bool=false;
				}
				else
				{
					strcpy(pszId_char,pszId);
					//memory leak fix
					delete[] pszId; pszId = NULL;
				}
			}
			if (pszId != NULL) delete[] pszId; pszId = NULL;
			continue;
		}

		if ( strncmp( &szCmdLine[i], winvncReconnectId, strlen(winvncReconnectId) ) == 0 )
			{
				i+=strlen("-");
				int start, end;
				char* pszId = NULL;
				start = i;
				end = start;
				while (szCmdLine[end] > ' ') end++;
				if (end - start > 0)
				{
					pszId = new char[end - start + 1];
					if (pszId != 0)
					{
						strncpy(pszId, &(szCmdLine[start]), end - start);
						pszId[end - start] = 0;
						pszId = _strupr(pszId);
					}
				}
				i = end;
			if (!vncService::PostAddConnectClient( pszId ))
			{
				PostAddConnectClient_bool=true;
				if (pszId==NULL)
				{
					PostAddConnectClient_bool_null=true;
					PostAddConnectClient_bool=false;
				}
				else
				{
					strcpy(pszId_char,pszId);
					//memory leak fix
					delete[] pszId; pszId = NULL;
				}
				}
			if (pszId != NULL) delete[] pszId; pszId = NULL;
			continue;
		}

		if (strncmp(&szCmdLine[i], winvncConnect, strlen(winvncConnect)) == 0)
		{
			if (!Injected_autoreconnect)
			{
				vncService::PostAddStopConnectClient();
			}
			// Add a new client to an existing copy of winvnc
			i+=strlen(winvncConnect);

			// First, we have to parse the command line to get the filename to use
			int start, end;
			start=i;
			while (szCmdLine[start] <= ' ' && szCmdLine[start] != 0) start++;
			end = start;
			while (szCmdLine[end] > ' ') end++;

			// Was there a hostname (and optionally a port number) given?
			if (end-start > 0)
			{
				char *name = new char[end-start+1];
				if (name != 0) {
					strncpy(name, &(szCmdLine[start]), end-start);
					name[end-start] = 0;

					int port = INCOMING_PORT_OFFSET;
					char *portp = strchr(name, ':');
					if (portp) {
						*portp++ = '\0';
						if (*portp == ':') {
							port = atoi(++portp);	// Port number after "::"
						} else {
							port = atoi(portp);	// Display number after ":"
						}
					}
					vnclog.Print(LL_STATE, VNCLOG("test... %s %d\n"),name,port);
					strcpy_s(dnsname,name);
					VCard32 address = VSocket::Resolve(name);
					delete [] name;
					if (address != 0) {
						// Post the IP address to the server
						// We can not contact a runnning service, permissions, so we must store the settings
						// and process until the vncmenu has been started
						vnclog.Print(LL_INTERR, VNCLOG("PostAddNewClient III \n"));
						if (!vncService::PostAddNewClientInit(address, port))
						{
						PostAddNewClient_bool=true;
						port_int=port;
						address_vcard=address;
						}
					}
					else
					{
						//ask for host,port
						PostAddNewClient_bool=true;
						port_int=0;
						address_vcard=0;
						Sleep(2000);
						//Beep(200,1000);
						return 0;
					}
				}
				i=end;
				continue;
			}
			else
			{
				// Tell the server to show the Add New Client dialog
				// We can not contact a runnning service, permissions, so we must store the settings
				// and process until the vncmenu has been started
				vnclog.Print(LL_INTERR, VNCLOG("PostAddNewClient IIII\n"));
				if (!vncService::PostAddNewClient(0, 0))
				{
				PostAddNewClient_bool=true;
				port_int=0;
				address_vcard=0;
				}
			}
			continue;
		}

		//adzm 2009-06-20
		if (strncmp(&szCmdLine[i], winvncRepeater, strlen(winvncRepeater)) == 0)
		{
			// set the default repeater host
			i+=strlen(winvncRepeater);

			// First, we have to parse the command line to get the host to use
			int start, end;
			start=i;
			while (szCmdLine[start] <= ' ' && szCmdLine[start] != 0) start++;
			end = start;
			while (szCmdLine[end] > ' ') end++;

			// Was there a hostname (and optionally a port number) given?
			if (end-start > 0)
			{
				if (g_szRepeaterHost) {
					delete[] g_szRepeaterHost;
					g_szRepeaterHost = NULL;
				}
				g_szRepeaterHost = new char[end-start+1];
				if (g_szRepeaterHost != 0) {
					strncpy(g_szRepeaterHost, &(szCmdLine[start]), end-start);
					g_szRepeaterHost[end-start] = 0;

					// We can not contact a runnning service, permissions, so we must store the settings
					// and process until the vncmenu has been started
					vnclog.Print(LL_INTERR, VNCLOG("PostAddNewRepeaterClient I\n"));
					if (!vncService::PostAddNewRepeaterClient())
					{
						PostAddNewRepeaterClient_bool=true;
						port_int=0;
						address_vcard=0;
					}
				}
				i=end;
				continue;
			}
			else
			{
				/*
				// Tell the server to show the Add New Client dialog
				// We can not contact a runnning service, permissions, so we must store the settings
				// and process until the vncmenu has been started
				vnclog.Print(LL_INTERR, VNCLOG("PostAddNewClient IIII\n"));
				if (!vncService::PostAddNewClient(0, 0))
				{
				PostAddNewClient_bool=true;
				port_int=0;
				address_vcard=0;
				}
				*/
			}
			continue;
		}

		// Either the user gave the -help option or there is something odd on the cmd-line!

		// Show the usage dialog
		MessageBoxSecure(NULL, winvncUsageText, sz_ID_WINVNC_USAGE, MB_OK | MB_ICONINFORMATION);
		break;
	};

	// If no arguments were given then just run
	if (!argfound)
	{
		if (!Myinit(hInstance))
		{
#ifdef CRASHRPT
			crUninstall();
#endif
			return 0;
		}
		int returnvalue= WinVNCAppMain();
#ifdef CRASHRPT
		crUninstall();
#endif
		return returnvalue;
	}
#ifdef CRASHRPT
	crUninstall();
#endif
	return 0;
}
Beispiel #24
0
int CMailMsg::MAPISend()
{

   TStrStrVector::iterator p;
   int                  nIndex = 0;
   size_t               nRecipients = 0;
   MapiRecipDesc*       pRecipients = NULL;
   MapiRecipDesc*       pOriginator = NULL;
   MapiRecipDesc*       pFirstRecipient = NULL;
   size_t               nAttachments = 0;
   MapiFileDesc*        pAttachments = NULL;
   ULONG                status = 0;
   MapiMessage          message;
   std::vector<MapiRecipDesc*>	buffersToFree;
   MapiRecipDesc*       pRecip;
   MapiRecipDesc		grecip;

   if (m_bReady || Initialize())
   {
	  LHANDLE hMapiSession;
	  status = m_lpMapiLogon(NULL, NULL, NULL, MAPI_NEW_SESSION | MAPI_LOGON_UI, 0, &hMapiSession);
	  if (SUCCESS_SUCCESS != status) {
		  return FALSE;
	  }

      nRecipients = m_to.size() + m_cc.size() + m_bcc.size() + m_from.size();
      if (nRecipients)
	  {
         pRecipients = new MapiRecipDesc[nRecipients];
		 memset(pRecipients, 0, nRecipients * sizeof  MapiRecipDesc);
	  }

      nAttachments = m_attachments.size();
      if (nAttachments)
         pAttachments = new MapiFileDesc[nAttachments];

      if (pRecipients)
      {
         pFirstRecipient = pRecipients;
         if (m_from.size())
         {
            // set from
			 if (cResolveName(hMapiSession, m_from.begin()->first.c_str(), &pOriginator) == SUCCESS_SUCCESS) {
				buffersToFree.push_back(pOriginator);
			 }
         }
         if (m_to.size())
         {
			 if (cResolveName(hMapiSession, m_to.begin()->first.c_str(), &pRecip) == SUCCESS_SUCCESS) {
				if (pFirstRecipient == NULL)
					pFirstRecipient = &pRecipients[nIndex];
				pRecip->ulRecipClass = MAPI_TO;
				memcpy(&pRecipients[nIndex], pRecip, sizeof pRecipients[nIndex]);
				buffersToFree.push_back(pRecip);
				nIndex++;
			 }
			 else
			 {
				 if (pFirstRecipient == NULL)
					 pFirstRecipient = &pRecipients[nIndex];
				 grecip.ulRecipClass = MAPI_TO;
				 grecip.lpEntryID = 0;
				 grecip.lpszName = 0;
				 grecip.ulEIDSize = 0;
				 grecip.ulReserved = 0;
				 grecip.lpszAddress = (LPTSTR)(LPCTSTR)m_to.begin()->first.c_str();
				 memcpy(&pRecipients[nIndex], &grecip, sizeof pRecipients[nIndex]);
				 nIndex++;
			 }
         }		
         if (m_cc.size())
         {
            // set cc's
            for (p = m_cc.begin(); p != m_cc.end(); p++, nIndex++)
            {
				if ( cResolveName(hMapiSession, p->first.c_str(), &pRecip) == SUCCESS_SUCCESS) {
					if (pFirstRecipient == NULL)
						pFirstRecipient = &pRecipients[nIndex];
					pRecip->ulRecipClass = MAPI_CC;
					memcpy(&pRecipients[nIndex], pRecip, sizeof pRecipients[nIndex]);
					buffersToFree.push_back(pRecip);
					nIndex++;
				}
            }
         }
   
         if (m_bcc.size())
         {
            // set bcc
            for (p = m_bcc.begin(); p != m_bcc.end(); p++, nIndex++)
            {
				if ( cResolveName(hMapiSession, p->first.c_str(), &pRecip) == SUCCESS_SUCCESS) {
					if (pFirstRecipient == NULL)
						pFirstRecipient = &pRecipients[nIndex];
					pRecip->ulRecipClass = MAPI_BCC;
					memcpy(&pRecipients[nIndex], pRecip, sizeof pRecipients[nIndex]);
					buffersToFree.push_back(pRecip);
					nIndex++;
				}
            }
         }
      }
      if (pAttachments)
      {
         // add attachments
         for (p = m_attachments.begin(), nIndex = 0;
              p != m_attachments.end(); p++, nIndex++)
         {
            pAttachments[nIndex].ulReserved        = 0;
            pAttachments[nIndex].flFlags           = 0;
            pAttachments[nIndex].nPosition         = 0;
            pAttachments[nIndex].lpszPathName      = (LPTSTR)p->first.c_str();
            pAttachments[nIndex].lpszFileName      = (LPTSTR)p->second.c_str();
            pAttachments[nIndex].lpFileType        = NULL;
         }
      }
	  memset(&message, 0, sizeof message);
      message.ulReserved                        = 0;
	  if (!m_sSubject.empty())
	      message.lpszSubject                       = (LPTSTR)m_sSubject.c_str();
	  else
		  message.lpszSubject = "No Subject";
	  if (!m_sMessage.empty())
	      message.lpszNoteText                      = (LPTSTR)m_sMessage.c_str();
	  else
		  message.lpszNoteText = "No Message Body";
      message.lpszMessageType                   = NULL;
      message.lpszDateReceived                  = NULL;
      message.lpszConversationID                = NULL;
      message.flFlags                           = 0;
      message.lpOriginator                      = pOriginator;
      message.nRecipCount                       = nIndex;
      message.lpRecips                          = pFirstRecipient;
      message.nFileCount                        = nAttachments;
      message.lpFiles                           = pAttachments;

      status = m_lpMapiSendMail(hMapiSession, 0, &message, MAPI_DIALOG, 0);
		  
      m_lpMapiLogoff(hMapiSession, NULL, 0, 0);
	  std::vector<MapiRecipDesc*>::iterator iter;
	  for (iter = buffersToFree.begin(); iter != buffersToFree.end(); iter++) {
		  m_lpMapiFreeBuffer(*iter);
	  }
if (SUCCESS_SUCCESS != status) {
				string txt;
				TCHAR buf[MAX_PATH];
				_tprintf_s(buf, "Message did not get sent due to error code %d.\r\n", status);
				txt = buf;
			switch (status)
			{  
			case MAPI_E_AMBIGUOUS_RECIPIENT:
				txt += "A recipient matched more than one of the recipient descriptor structures and MAPI_DIALOG was not set. No message was sent.\r\n" ;
				break;
			case MAPI_E_ATTACHMENT_NOT_FOUND:
				txt += "The specified attachment was not found. No message was sent.\r\n" ;
				break;
			case MAPI_E_ATTACHMENT_OPEN_FAILURE:
				txt += "The specified attachment could not be opened. No message was sent.\r\n" ;
				break;
			case MAPI_E_BAD_RECIPTYPE:
				txt += "The type of a recipient was not MAPI_TO, MAPI_CC, or MAPI_BCC. No message was sent.\r\n" ;
				break;
			case MAPI_E_FAILURE:
				txt += "One or more unspecified errors occurred. No message was sent.\r\n" ;
				break;
			case MAPI_E_INSUFFICIENT_MEMORY:
				txt += "There was insufficient memory to proceed. No message was sent.\r\n" ;
				break;
			case MAPI_E_INVALID_RECIPS:
				txt += "One or more recipients were invalid or did not resolve to any address.\r\n" ;
				break;
			case MAPI_E_LOGIN_FAILURE:
				txt += "There was no default logon, and the user failed to log on successfully when the logon dialog box was displayed. No message was sent.\r\n" ;
				break;
			case MAPI_E_TEXT_TOO_LARGE:
				txt += "The text in the message was too large. No message was sent.\r\n" ;
				break;
			case MAPI_E_TOO_MANY_FILES:
				txt += "There were too many file attachments. No message was sent.\r\n" ;
				break;
			case MAPI_E_TOO_MANY_RECIPIENTS:
				txt += "There were too many recipients. No message was sent.\r\n" ;
				break;
			case MAPI_E_UNKNOWN_RECIPIENT:
				txt += "A recipient did not appear in the address list. No message was sent.\r\n" ;
				break;
			case MAPI_E_USER_ABORT:
				txt += "The user canceled one of the dialog boxes. No message was sent.\r\n" ;
				break;
			default:
				txt += "Unknown error code.\r\n" ;
				break;
			}
			::MessageBox(0, txt.c_str(), "Error", MB_OK);
}

      if (pRecipients)
         delete [] pRecipients;

      if (nAttachments)
         delete [] pAttachments;
   }

   if (SUCCESS_SUCCESS == status)
	   return 1;
   if (MAPI_E_USER_ABORT == status)
	   return -1;
   // other failure
   return 0;
}
Beispiel #25
0
VOID CLog::OutputLog(DWORD logLevel, TCHAR* logString)
{
	SYSTEMTIME current;
	GetLocalTime(&current);

	TCHAR szCurrentTime[16] = {0,};
	_stprintf_s(szCurrentTime, 16, _T("%02u:%02u:%02u"),
		current.wHour,
		current.wMinute,
		current.wSecond);

	TCHAR* szLogLevel = NULL;
	
	switch (logLevel)
	{
	case LOG_NORMAL:
		szLogLevel = L"normal";
		break;

	case LOG_WARNING:
		szLogLevel = L"warning";
		break;

	case LOG_ERROR:
		szLogLevel = L"error";
		break;

	default:
		szLogLevel = L"unknown";
	}


	TCHAR szTotalLog[2048] = {0,};
	_stprintf_s(szTotalLog, 1024, _T("[%s] [%.8s]: %s\n"),
		szCurrentTime, szLogLevel, logString);

#ifdef _DEBUG
	OutputDebugString(szTotalLog);
#endif

#ifdef _CONSOLE
	_tprintf_s(szTotalLog);
#endif

	if(m_FileTime.wYear != current.wYear
		|| m_FileTime.wMonth != current.wMonth
		|| m_FileTime.wDay != current.wDay
		|| m_FileTime.wHour != current.wHour)
	{
		m_FileStream.close();

		_stprintf_s(m_FileName, MAX_PATH, _T("%s%s %04u-%02u-%02u %02u.log"),
			m_FileDirectory.c_str(),
			m_ExeFileName.c_str(),
			m_FileTime.wYear,
			m_FileTime.wMonth,
			m_FileTime.wDay,
			m_FileTime.wHour);

		m_FileStream.open(m_FileName, std::ios::app);

		m_FileTime = current;
	}

	m_FileStream << szTotalLog;;
	m_FileStream.flush();

}
Beispiel #26
0
void ReadTiFileHeader(FILE *infile, TIFILE_t *tifile) {
	char headerString[8];
	int i, tmp;

	fread(headerString, 1, 8, infile);
	rewind(infile);
	
	if (!_strnicmp(headerString, DETECT_STR, 8) ||
		!_strnicmp(headerString, DETECT_CMP_STR, 8)) {
		tifile->type = SAV_TYPE;
		return;
	}

	if (!_strnicmp(headerString, FLASH_HEADER, 8)) {
		tifile->type = FLASH_TYPE;
		tifile->flash = (TIFLASH_t*) malloc(sizeof(TIFLASH_t));
		ZeroMemory(tifile->flash, sizeof(TIFLASH_t));
		if (tifile->flash == NULL) {
			FreeTiFile(tifile);
			return;
		}

		unsigned char *ptr = (unsigned char *) tifile->flash;
		for(i = 0; i < TI_FLASH_HEADER_SIZE && !feof(infile); i++) {
			tmp = fgetc(infile);
			if (tmp == EOF) {
				_tprintf_s(_T("failed to get the whole header\n"));
				fclose(infile);
				FreeTiFile(tifile);
				return;
			}
			ptr[i] = tmp;
		}
		return;
	}

	/* It maybe a rom if it doesn't have the Standard header */
	if (_strnicmp(headerString, "**TI73**", 8) &&
		_strnicmp(headerString, "**TI82**", 8) &&
		_strnicmp(headerString, "**TI83**", 8) &&
		_strnicmp(headerString, "**TI83F*", 8) &&
		_strnicmp(headerString, "**TI85**", 8) &&
		_strnicmp(headerString, "**TI86**", 8)) {
		tifile->type = ROM_TYPE;
		return;
	}

	/* Import file Header */
	unsigned char *ptr = (unsigned char *) tifile;
	for(i = 0; i < TI_FILE_HEADER_SIZE && !feof(infile); i++) {
		tmp = fgetc(infile);
		if (tmp == EOF) {
			FreeTiFile(tifile);
			return;
		}
		ptr[i] = tmp;
	}

	if (!_strnicmp((char *) tifile->sig, "**TI73**", 8)) tifile->model = TI_73;
	else if (!_strnicmp((char *) tifile->sig, "**TI82**", 8)) tifile->model = TI_82;
	else if (!_strnicmp((char *) tifile->sig, "**TI83**", 8)) tifile->model = TI_83;
	else if (!_strnicmp((char *) tifile->sig, "**TI83F*", 8)) tifile->model = TI_83P;
	else if (!_strnicmp((char *) tifile->sig, "**TI85**", 8)) tifile->model = TI_85;
	else if (!_strnicmp((char *) tifile->sig, "**TI86**", 8)) tifile->model = TI_86;
	else {
		FreeTiFile(tifile);
		return;
	}
	return;
}
BOOL CAlarmCenterApp::InitInstance()
{
	/*{
		bool connect_by_sse_or_ip_ = true;
		std::string cloud_sse_id_ = "";
		std::string device_ipv4_ = "";
		int device_port_ = 0;
		std::wstring user_name_ = L"";
		int user_id = 0;
		std::wstring _device_note = L"";
		int _id = 0;

		CString sql;
		sql.Format(L"update table_device_info_jovision set \
connect_by_sse_or_ip=%d,\
cloud_sse_id='%s',\
device_ipv4='%s',\
device_port=%d,\
user_name='%s',\
user_passwd='%s',\
user_info_id=%d,\
device_note='%s' where id=%d",
connect_by_sse_or_ip_ ? 1 : 0,
utf8::a2w(cloud_sse_id_).c_str(),
utf8::a2w(device_ipv4_).c_str(),
device_port_,
user_name_.c_str(),
user_id,
_device_note.c_str(),
_id);

		JLOG(sql);
	}*/


	do {
		if (IfProcessRunning())
			break;
		auto log = log::get_instance();
		log->set_output_to_dbg_view();
		log->set_line_prifix("HB");
		log->set_log_file_foler(get_exe_path_a() + "\\Log");
		log->set_log_file_prefix("AlarmCenter");
		log->set_output_to_file();
		
		JLOG(L"AlarmCenter startup.\n");
		AUTO_LOG_FUNCTION;

		int	nRet;
		WSAData	wsData;

		nRet = WSAStartup(MAKEWORD(2, 2), &wsData);
		if (nRet < 0) {
			JLOG(L"Can't load winsock.dll.\n");
			break;
		}


#pragma region init crashrpt
		// Place all significant initialization in InitInstance
		// Define CrashRpt configuration parameters
		CR_INSTALL_INFO info;
		memset(&info, 0, sizeof(CR_INSTALL_INFO));
		info.cb = sizeof(CR_INSTALL_INFO);
		info.pszAppName = _T("AlarmCenter");
		static CString version;
		detail::GetProductVersion(version);
		info.pszAppVersion = version;
		info.pszEmailSubject = _T("AlarmCenter Error Report");
		info.pszEmailTo = _T("*****@*****.**");
		info.pszUrl = _T("http://113.140.30.118/crashrpt.php");
		info.uPriorities[CR_HTTP] = 3;  // First try send report over HTTP 
		info.uPriorities[CR_SMTP] = 2;  // Second try send report over SMTP  
		info.uPriorities[CR_SMAPI] = 1; // Third try send report over Simple MAPI    
										// Install all available exception handlers
		info.dwFlags |= CR_INST_ALL_POSSIBLE_HANDLERS;
		// Restart the app on crash 
		info.dwFlags |= CR_INST_APP_RESTART;
		info.dwFlags |= CR_INST_SEND_QUEUED_REPORTS;
		//info.pszRestartCmdLine = _T("/restart");
		// Define the Privacy Policy URL 
		//info.pszPrivacyPolicyURL = _T("http://myapp.com/privacypolicy.html");

		// Install crash reporting
		int nResult = crInstall(&info);
		if (nResult != 0) {
			// Something goes wrong. Get error message.
			TCHAR szErrorMsg[512] = _T("");
			crGetLastErrorMsg(szErrorMsg, 512);
			_tprintf_s(_T("%s\n"), szErrorMsg);
			MessageBox(nullptr, szErrorMsg, L"Error", MB_ICONERROR);
			break;
		}

		// Set crash callback function
		//crSetCrashCallback(CrashCallback, nullptr);

		// Add our log file to the error report
		crAddFile2(utf8::a2w(log::get_instance()->get_log_file_path()).c_str(), nullptr, _T("Log File"), CR_AF_MAKE_FILE_COPY);

		// We want the screenshot of the entire desktop is to be added on crash
		crAddScreenshot2(CR_AS_VIRTUAL_SCREEN, 0);

		// Add a named property that means what graphics adapter is
		// installed on user's machine
		//crAddProperty(_T("VideoCard"), _T("nVidia GeForce 8600 GTS"));



#pragma endregion

		auto res = res::get_instance();
		auto cfg = util::CConfigHelper::get_instance();
		auto lang = cfg->get_language();
		auto path = get_exe_path();
#ifdef _DEBUG
		path = path.substr(0, path.find_last_of(L'\\'));
		path += L"\\installer";
#endif
		switch (lang) {	
		case util::AL_TAIWANESE:
			res->parse_file(path + L"\\lang\\zh-tw.txt");
			SetThreadUILanguage(MAKELCID(MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_TRADITIONAL), SORT_DEFAULT));
			break;
		case util::AL_ENGLISH:
			res->parse_file(path + L"\\lang\\en-us.txt");
			SetThreadUILanguage(MAKELCID(MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), SORT_DEFAULT));
			break;
		case util::AL_CHINESE:
		default:
			res->parse_file(path + L"\\lang\\zh-cn.txt");
			SetThreadUILanguage(MAKELCID(MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED), SORT_DEFAULT));
			break;
		}

		CAppResource::get_instance();

		// InitCommonControlsEx() is required on Windows XP if an application
		// manifest specifies use of ComCtl32.dll version 6 or later to enable
		// visual styles.  Otherwise, any window creation will fail.
		INITCOMMONCONTROLSEX InitCtrls;
		InitCtrls.dwSize = sizeof(InitCtrls);
		// Set this to include all the common control classes you want to use
		// in your application.
		InitCtrls.dwICC = ICC_WIN95_CLASSES;
		InitCommonControlsEx(&InitCtrls);

		CWinApp::InitInstance();

		AfxEnableControlContainer();

		// Create the shell manager, in case the dialog contains
		// any shell tree view or shell list view controls.
		auto pShellManager = std::make_unique<CShellManager>();

		// Activate "Windows Native" visual manager for enabling themes in MFC controls
		//CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows));

		// Standard initialization
		// If you are not using these features and wish to reduce the size
		// of your final executable, you should remove from the following
		// the specific initialization routines you do not need
		// Change the registry key under which our settings are stored
		// You should modify this string to be something appropriate
		// such as the name of your company or organization
		SetRegistryKey(_T("Local AppWizard-Generated Applications"));

		CLoginDlg loginDlg;
		if (loginDlg.DoModal() != IDOK) {
			JLOG(L"user canceled login.\n");
			break;
		}

		CSetupNetworkDlg setupDlg;
		if (setupDlg.DoModal() != IDOK) {
			JLOG(L"user canceled setup network.\n");
			break;
		}

		CAlarmCenterDlg dlg;
		m_pMainWnd = &dlg;
		INT_PTR nResponse = dlg.DoModal();
		if (nResponse == IDOK) {

		} else if (nResponse == IDCANCEL) {

		} else if (nResponse == -1) {
			TRACE(L"Warning: dialog creation failed, so application is terminating unexpectedly.\n");
			TRACE(L"Warning: if you are using MFC controls on the dialog, you cannot #define _AFX_NO_MFC_CONTROLS_IN_DIALOGS.\n");
		}

		

	} while (false);

	
	//video::ezviz::sdk_mgr_ezviz::release_singleton();
	

	// Since the dialog has been closed, return FALSE so that we exit the
	//  application, rather than start the application's message pump.
	return FALSE;
}
Beispiel #28
0
VOID CALLBACK TimerAPCProc( LPVOID lpArg , DWORD timerLowVal , DWORD timerHighVal )
{
	_tprintf_s( _T( "%s" ) , ( TCHAR* )lpArg );
	MessageBeep( MB_ICONEXCLAMATION );
}
Beispiel #29
0
static HRESULT TypeDescToString(__inout CNktStringW &cStrDestW, __in TYPEDESC *lpTypeDesc,
                                __in ITypeInfo *lpTypeInfo, __in BOOL bDependencyCheck)
{
  static const LPWSTR szVT_W[] = {
    L"void",             //VT_EMPTY           = 0,   // [V]   [P]  nothing
    L"null",             //VT_NULL            = 1,   // [V]        SQL style Null
    L"short",            //VT_I2              = 2,   // [V][T][P]  2 byte signed int
    L"long",             //VT_I4              = 3,   // [V][T][P]  4 byte signed int
    L"single",           //VT_R4              = 4,   // [V][T][P]  4 byte real
    L"double",           //VT_R8              = 5,   // [V][T][P]  8 byte real
    L"CURRENCY",         //VT_CY              = 6,   // [V][T][P]  currency
    L"DATE",             //VT_DATE            = 7,   // [V][T][P]  date
    L"BSTR",             //VT_BSTR            = 8,   // [V][T][P]  binary string
    L"IDispatch*",       //VT_DISPATCH        = 9,   // [V][T]     IDispatch FAR*
    L"SCODE",            //VT_ERROR           = 10,  // [V][T]     SCODE
    L"boolean",          //VT_BOOL            = 11,  // [V][T][P]  True=-1, False=0
    L"VARIANT",          //VT_VARIANT         = 12,  // [V][T][P]  VARIANT FAR*
    L"IUnknown*",        //VT_UNKNOWN         = 13,  // [V][T]     IUnknown FAR*
    L"wchar_t",          //VT_WBSTR           = 14,  // [V][T]     wide binary string
    L"",                 //                   = 15,
    L"char",             //VT_I1              = 16,  //    [T]     signed char
    L"unsigned char",    //VT_UI1             = 17,  //    [T]     unsigned char
    L"unsigned short",   //VT_UI2             = 18,  //    [T]     unsigned short
    L"unsigned long",    //VT_UI4             = 19,  //    [T]     unsigned short
    L"int64",            //VT_I8              = 20,  //    [T][P]  signed 64-bit int
    L"uint64",           //VT_UI8             = 21,  //    [T]     unsigned 64-bit int
    L"int",              //VT_INT             = 22,  //    [T]     signed machine int
    L"unsigned int",     //VT_UINT            = 23,  //    [T]     unsigned machine int
    L"void",             //VT_VOID            = 24,  //    [T]     C style void
    L"HRESULT",          //VT_HRESULT         = 25,  //    [T]
    L"PTR",              //VT_PTR             = 26,  //    [T]     pointer type
    L"SAFEARRAY",        //VT_SAFEARRAY       = 27,  //    [T]     (use VT_ARRAY in VARIANT)
    L"CARRAY",           //VT_CARRAY          = 28,  //    [T]     C style array
    L"USERDEFINED",      //VT_USERDEFINED     = 29,  //    [T]     user defined type
    L"LPSTR",            //VT_LPSTR           = 30,  //    [T][P]  null terminated string
    L"LPWSTR",           //VT_LPWSTR          = 31,  //    [T][P]  wide null terminated string
    L"",                 //                   = 32,
    L"",                 //                   = 33,
    L"",                 //                   = 34,
    L"",                 //                   = 35,
    L"",                 //                   = 36,
    L"",                 //                   = 37,
    L"",                 //                   = 38,
    L"",                 //                   = 39,
    L"",                 //                   = 40,
    L"",                 //                   = 41,
    L"",                 //                   = 42,
    L"",                 //                   = 43,
    L"",                 //                   = 44,
    L"",                 //                   = 45,
    L"",                 //                   = 46,
    L"",                 //                   = 47,
    L"",                 //                   = 48,
    L"",                 //                   = 49,
    L"",                 //                   = 50,
    L"",                 //                   = 51,
    L"",                 //                   = 52,
    L"",                 //                   = 53,
    L"",                 //                   = 54,
    L"",                 //                   = 55,
    L"",                 //                   = 56,
    L"",                 //                   = 57,
    L"",                 //                   = 58,
    L"",                 //                   = 59,
    L"",                 //                   = 60,
    L"",                 //                   = 61,
    L"",                 //                   = 62,
    L"",                 //                   = 63,
    L"FILETIME",         //VT_FILETIME        = 64,  //       [P]  FILETIME
    L"BLOB",             //VT_BLOB            = 65,  //       [P]  Length prefixed bytes
    L"STREAM",           //VT_STREAM          = 66,  //       [P]  Name of the stream follows
    L"STORAGE",          //VT_STORAGE         = 67,  //       [P]  Name of the storage follows
    L"STREAMED_OBJECT",  //VT_STREAMED_OBJECT = 68,  //       [P]  Stream contains an object
    L"STORED_OBJECT",    //VT_STORED_OBJECT   = 69,  //       [P]  Storage contains an object
    L"BLOB_OBJECT",      //VT_BLOB_OBJECT     = 70,  //       [P]  Blob contains an object
    L"CF",               //VT_CF              = 71,  //       [P]  Clipboard format
    L"CLSID",            //VT_CLSID           = 72   //       [P]  A Class ID
  };
  HRESULT hRes;
  CNktStringW cStrTempW;

  if (lpTypeDesc->vt == VT_PTR)
  {
    hRes = TypeDescToString(cStrTempW, lpTypeDesc->lptdesc, lpTypeInfo, bDependencyCheck);
    if (FAILED(hRes))
      return hRes;
    if (cStrDestW.Concat(cStrTempW) == FALSE)
      return E_OUTOFMEMORY;
    if (bDependencyCheck == FALSE)
    {
      //don't add unneeded stuff if dependecy check
      if (cStrDestW.Concat(L"*") == FALSE)
        return E_OUTOFMEMORY;
    }
    else
    {
      //add a separator
      if (cStrDestW.Concat(L" ") == FALSE)
        return E_OUTOFMEMORY;
    }
    return S_OK;
  }
  if ((lpTypeDesc->vt & 0x0FFF) == VT_SAFEARRAY)
  {
    if (bDependencyCheck == FALSE)
    {
      //don't add unneeded stuff if dependecy check
      if (cStrDestW.Concat(L"SAFEARRAY*") == FALSE)
        return E_OUTOFMEMORY;
    }
    return S_OK;
  }
  if ((lpTypeDesc->vt & 0x0FFF) == VT_CARRAY)
  {
    USHORT i;

    hRes = TypeDescToString(cStrTempW, &(lpTypeDesc->lpadesc->tdescElem), lpTypeInfo, bDependencyCheck);
    if (FAILED(hRes))
      return hRes;
    if (cStrDestW.Concat(cStrTempW) == FALSE)
      return E_OUTOFMEMORY;
    if (bDependencyCheck == FALSE)
    {
      //don't add unneeded stuff if dependecy check
      for (i=0; i<lpTypeDesc->lpadesc->cDims; i++)
      {
        if (cStrDestW.Concat(L"[") == FALSE ||
            cStrDestW.Concat(lpTypeDesc->lpadesc->rgbounds[i].cElements) == FALSE ||
            cStrDestW.Concat(L"]") == FALSE)
          return E_OUTOFMEMORY;
      }
    }
    else
    {
      //add a separator
      if (cStrDestW.Concat(L" ") == FALSE)
        return E_OUTOFMEMORY;
    }
    return S_OK;
  }
  if (lpTypeDesc->vt == VT_USERDEFINED)
  {
    return CustomTypeToString(cStrDestW, lpTypeDesc->hreftype, lpTypeInfo);
  }
  if ((lpTypeDesc->vt & (~0xF000)) > VT_CLSID)
  {
    _tprintf_s(_T("Error: Unsupported type '%04X' found.\n"), lpTypeDesc->vt);
    return E_NOTIMPL;
  }
  if (bDependencyCheck == FALSE)
  {
    //don't add unneeded stuff if dependecy check
    if (cStrDestW.Concat(szVT_W[lpTypeDesc->vt & (~0xF000)]) == FALSE)
      return E_OUTOFMEMORY;
  }
  return S_OK;
}
Beispiel #30
0
static HRESULT ProcessConst(__in FILE *fp, __in WORD nIndex, __in TYPEATTR* lpTypeAttr,
                            __in ITypeInfo *lpTypeInfo, __in SIZE_T nIndent, __in BOOL bShowConst)
{
  CAutoVarDesc cVarDesc;
  CNktStringW cStrTempW;
  CNktComBStr bstrMemberName;
  BSTR bstr;
  HRESULT hRes;
  UINT nNamesCount;
  CNktComVariant vtValue;

  hRes = cVarDesc.Set(lpTypeInfo, nIndex);
  EXIT_ON_ERROR(hRes);
  if (cVarDesc->varkind != VAR_CONST)
  {
    _tprintf_s(_T("Error: Constant not declared as constant.\n"));
    return E_NOTIMPL;
  }
  cStrTempW.Empty();
  hRes = TypeDescToString(cStrTempW, &(cVarDesc->elemdescVar.tdesc), lpTypeInfo, FALSE);
  EXIT_ON_ERROR(hRes);
  hRes = ::VariantChangeType(&vtValue, cVarDesc->lpvarValue, 0, VT_BSTR);
  if (FAILED(hRes))
  {
    WCHAR szTempBufW[32], *sW;

    if (cVarDesc->lpvarValue->vt != VT_ERROR && cVarDesc->lpvarValue->vt != VT_HRESULT)
      return hRes;
    sW = miscGetScodeString(cVarDesc->lpvarValue->scode, szTempBufW);
    vtValue.sVt.vt = VT_BSTR;
    vtValue.sVt.bstrVal = ::SysAllocString(sW);
    if (vtValue.sVt.bstrVal == NULL)
      return E_OUTOFMEMORY;
  }
  hRes = lpTypeInfo->GetNames(cVarDesc->memid, &bstr, 1, &nNamesCount);
  EXIT_ON_ERROR(hRes);
  if (nNamesCount == 0 || bstr == NULL)
  {
    _tprintf_s(_T("Error: Unnamed variables are not supported.\n"));
    return E_NOTIMPL;
  }
  bstrMemberName.Attach(bstr);
  WRITEINDENT_AND_CHECK(fp, nIndent);
  if (bShowConst != FALSE)
  {
    WRITEANSI_AND_CHECK(fp, "const ");
    WRITEWIDE_AND_CHECK(fp, (LPWSTR)cStrTempW);
    WRITEANSI_AND_CHECK(fp, " ");
  }
  WRITEBSTR_AND_CHECK(fp, bstrMemberName);
  WRITEANSI_AND_CHECK(fp, " = ");
  if (cVarDesc->lpvarValue->vt == VT_BSTR)
  {
    WRITEANSI_AND_CHECK(fp, "\"");
    WRITEBSTR_AND_CHECK(fp, vtValue.sVt.bstrVal);
    WRITEANSI_AND_CHECK(fp, "\"");
  }
  else
  {
    WRITEBSTR_AND_CHECK(fp, vtValue.sVt.bstrVal);
  }
  if (bShowConst != FALSE)
  {
    WRITEANSI_AND_CHECK(fp, ";\r\n");
  }
  return S_OK;
}