C++ MFC How to prevent duplicate values in each Ch? - c++

I have the following code:
And I would like to select one Ch without the number which has been selected in the other Ch.
For example, in Ch5, "1","2","3","37" can not be selected.
BOOL CMaintenanceHeadDispenserDlg::OnInitDialog()
{
CMaintenanceChildDlg::OnInitDialog();
CRect rc(0, 0, 0, 0);
m_edtDist.Create( NULL, NULL, WS_CHILD|WS_VISIBLE|WS_DISABLED, rc, this, IDC_EDT_MT_HEAD_DISPENSER_DIST );
m_edtDist.SetInputMode( 1 );
m_edtDist.SetInputRange( 999.999, 0.0 );
m_edtDist.EnableRightInputMode( TRUE, 2 );
m_edtOutput.Create(NULL, WS_CHILD|WS_VISIBLE|WS_DISABLED, rc, this, IDC_EDT_MT_HEAD_DISPENSER_OUTPUT);
CDeviceConfigDispenserController* p = CDeviceConfigDispenserController::GetInstance();
SDeviceConfigDispenser d;
p->GetData( d );
m_DispenserChInfoSet.GetChMap(m_mapCh);
for( int i = 0; i < 5; i++ ) {
m_cmbCh[i].ResetContent();
m_cmbCh[i].SetScrollCnt(5);
m_cmbCh[i].SetHitTrace( TRUE );
m_edtCh[i].Create(NULL,NULL,WS_VISIBLE|WS_CHILD|WS_DISABLED,rc,this,IDC_EDT_MT_HEAD_DISPENSER_CH1 + i);
m_edtCh[i].SetLimitTextNum(32);
int itemCnt = 0;
CString strCh;
for( map<int, CString>::iterator it = m_mapCh.begin(); it != m_mapCh.end(); it++ ) {
strCh.Format(_T("%d"), it->first);
m_cmbCh[i].InsertString(itemCnt, strCh);
m_cmbCh[i].SetItemData(itemCnt, it->first);
if( d.nUseCh[i] == it->first ) {
m_cmbCh[i].SetCurSel( itemCnt );
m_edtCh[i].SetString( it->second );
}
itemCnt++;
}
m_rdoCh[i].SetCheck( BST_UNCHECKED );
}
afx_msg LRESULT CMaintenanceHeadDispenserDlg::OnCbxSelchanged(WPARAM wParam, LPARAM lParam)
{
//int j = 0; //ou
for( int i = 0; i < 5; i++ ) {
if( m_cmbCh[i].m_hWnd == (HWND)lParam )
{
int Cnt = m_cmbCh[i].GetCount();
if( (int)wParam < Cnt && (int)wParam >= 0) {
m_cmbCh[i].SetCurSel( (int)wParam );
int Index = (int)m_cmbCh[i].GetItemData( m_cmbCh[i].GetCurSel() );
map<int, CString>::iterator it = m_mapCh.find( Index );
if( it != m_mapCh.end() ) {
m_edtCh[i].SetString( it->second );
}
break;
}
}
}

Related

LDAP C++ why is ldap_result always busy?

I tried copying this example: https://docs.oracle.com/cd/E19957-01/817-6707/search.html
I am trying to get the DN to bind to a user. But when searching ldap_result always says that the server is busy. Is there something else I need to do to get this to work?
LDAP *ld = NULL;
int iDebug = session.ini["ldap_debug_level"].Int32();
string sHostIP = session.ini["ldap_host"];
string sPort = session.ini["ldap_port"];
string sURL = sHostIP+":"+sPort;
int iErr;
iErr = ldap_initialize( &ld, sURL.c_str() );
if( iErr != LDAP_SUCCESS )
{
ldap_unbind(ld);
return false;
}
int iVersion = LDAP_VERSION3;
if( ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &iVersion ) != LDAP_OPT_SUCCESS )
{
ldap_unbind(ld);
return false;
}
string sLDAPPW = session.ini["ldap_server_pw"];
struct berval pServerPassword = { 0, NULL };
pServerPassword.bv_val = ber_strdup( &sLDAPPW[0] );
pServerPassword.bv_len = strlen( pServerPassword.bv_val );
//mysterious code required to prevent crashing
int nsctrls = 0;
LDAPControl c;
c.ldctl_oid = LDAP_CONTROL_PASSWORDPOLICYREQUEST;
c.ldctl_value.bv_val = NULL;
c.ldctl_value.bv_len = 0;
c.ldctl_iscritical = 0;
LDAPControl sctrl[3];
sctrl[nsctrls] = c;
LDAPControl *sctrls[4];
sctrls[nsctrls] = &sctrl[nsctrls];
sctrls[++nsctrls] = NULL;
LDAPControl **sctrlsp = NULL;
if ( nsctrls )
{
sctrlsp = sctrls;
}
string sBindDN = session.ini["ldap_bind_dn"];
ber_int_t iMsgid;
iErr = ldap_sasl_bind( ld, sBindDN.c_str(), LDAP_SASL_SIMPLE, &pServerPassword, sctrlsp, NULL, &iMsgid );
ber_memfree( pServerPassword.bv_val );
if( iErr != LDAP_SUCCESS )
{
ldap_unbind(ld);
return false;
}
string sBaseDN = session.ini["ldap_base_dn"];
string sFilters = "(uid="+sUserName+")";
LDAPMessage *res;
iErr = ldap_search_ext(ld, // LDAP * ld
&sBaseDN[0], // char * base
LDAP_SCOPE_SUBORDINATE,// int scope
&sFilters[0], // char * filter
NULL, // char * attrs[]
0, // int attrsonly
NULL, // LDAPControl ** serverctrls
NULL, // LDAPControl ** clientctrls
NULL, //struct timeval *timeoutp
LDAP_NO_LIMIT, //int sizelimit
&iMsgid //ber_int_t iMsgid
);
if (iErr != LDAP_SUCCESS)
{
ldap_unbind(ld);
return false;
}
struct timeval zerotime;
zerotime.tv_sec = zerotime.tv_usec = 0L;
int i, parse_rc, finished = 0, num_entries = 0, num_refs = 0;
char *a, *dn, *matched_msg = NULL, *error_msg = NULL;
BerElement *ber;
char **vals, **referrals;
LDAPControl **serverctrls;
while ( !finished )
{
iErr = ldap_result( ld, iMsgid, LDAP_MSG_ONE, &zerotime, &res );
switch ( iErr )
{
case -1:
Log(1, "BasicAuthenticate: error in ldap_result:{}", ldap_err2string(iErr));
ldap_unbind(ld);
return false;
break;
case 0:
// The timeout period specified by zerotime was exceeded keep polling
Log(1, "BasicAuthenticate: server busy: keep polling");
sleep(1);
break;
case LDAP_RES_SEARCH_ENTRY:
num_entries++;
//Get and print the DN of the entry.
if (( dn = ldap_get_dn( ld, res )) != NULL )
{
Log (1, "ldap_get_dn: {}", dn );
ldap_memfree( dn );
}
for ( a = ldap_first_attribute( ld, res, &ber ); a != NULL; a = ldap_next_attribute( ld, res, ber ) )
{
// Get and print all values for each attribute.
if (( vals = ldap_get_values( ld, res, a )) != NULL )
{
for ( i = 0; vals[ i ] != NULL; i++ )
{
Log (1, "ldap_get_values: {}:{}", a, vals[ i ] );
}
ldap_value_free( vals );
}
ldap_memfree( a );
}
if ( ber != NULL )
{
ber_free( ber, 0 );
}
ldap_msgfree( res );
break;
case LDAP_RES_SEARCH_REFERENCE:
num_refs++;
parse_rc = ldap_parse_reference( ld, res, &referrals, NULL, 1 );
if ( parse_rc != LDAP_SUCCESS )
{
ldap_unbind(ld);
return false;
}
if ( referrals != NULL )
{
for ( i = 0; referrals[ i ] != NULL; i++ )
{
Log(1, "BasicAuthenticate: Search reference:{}", referrals[ i ]);
}
ldap_value_free( referrals );
}
break;
case LDAP_RES_SEARCH_RESULT:
finished = 1;
parse_rc = ldap_parse_result( ld, res, &iErr, &matched_msg, &error_msg, NULL, &serverctrls, 1 );
if ( parse_rc != LDAP_SUCCESS )
{
kDebugLog(1, "BasicAuthenticate: error in ldap_parse_result:{}", ldap_err2string(parse_rc));
ldap_unbind(ld);
return false;
}
break;
default:
break;
}
}
The error I get is:
BasicAuthenticate: server busy keep polling
BasicAuthenticate: error in ldap_parse_result:Server is busy
Am I missing a line of code so the server won't be busy? Is there some sort of incompatibility with the methods I'm using?

Memory management routine error

I'm trying to use FP routine, but it doesn't work...Why?
This is my code:
int output = FindPattern(0x0042A000, 0x2000, "\x68\x00\x00\x00\x00\xFF\x76\x08\x89\x46\x44", "x????xxxxxx");
if (output > -1) {
ReadProcessMemory(hProcHandle, (PVOID)address, &value2, sizeof(value2), NULL);
}
Function:
int FindPattern(int start_offset, int size, const char * pattern, const char * mask)
{
int pos = 0;
for (int retAddress = start_offset; retAddress < start_offset + size; retAddress++)
{
if (*(const char*)retAddress == pattern[pos] || mask[pos] == '?')
{
if (mask[pos+1] == '\0')
return retAddress+1;
pos++;
}
else
pos = 0;
}
return -1;
}
I also tried:
DWORD output = FindPattern(hProcHandle, "\x68\x00\x00\x00\x00\xFF\x76\x08\x89\x46\x44", "x????xxxxxx");
bool VerifyAddress(HANDLE hwnd, DWORD dwAddress, char *bMask, char *szMask )
{
PBYTE *pTemp = { 0 };
for ( int i = 0; *szMask; ++szMask, ++bMask, ++i )
{
if ( !ReadProcessMemory( hwnd, reinterpret_cast<LPCVOID>(dwAddress + i), &pTemp, sizeof(pTemp), 0 ) ){
return false;
}
if ( *szMask == 'x' && (char)pTemp != *bMask){
return false;
}
}
return true;
}
DWORD FindPattern(HANDLE hwnd, char* bMask, char *szMask )
{
for ( DWORD dwCurrentAddress = 0x4FFFFFF; dwCurrentAddress < 0x7FFFFFF; dwCurrentAddress++ ){
if ( VerifyAddress( hwnd, dwCurrentAddress, bMask, szMask )) {
return dwCurrentAddress;
}
}
But with these codes I get always
Unhandled exception at 0x01034BB1 in Program.exe: 0xC0000005: Access
violation reading location 0x02343DA2.
This code:
int output = FindPattern(0x0042A000, 0x2000,
indicates that you are using address 0x0042A000 local to your process, so you are iterating over some random addresses in your process which is Undefined Behaviour and ends with exception.
ReadProcessMemory copies specified memory from some other process to your process and stores in in memory buffer you provide in this function call as lpBuffer parameter.

_ttoi win c++ assertion failure

i have this code:
BOOLEAN Recurse = FALSE;
DWORD NumPasses = 1;
int _tmain( int argc, TCHAR *argv[] )
{
BOOL foundFileArg = FALSE;
int i;
if( argc < 2 ) {
return Usage( argv[0] );
}
for( i = 1; i < argc; i++ ) {
if( !_tcsicmp( argv[i], TEXT("/s") ) ||
!_tcsicmp( argv[i], TEXT("-s") )) {
Recurse = TRUE;
} else if( !_tcsicmp( argv[i], TEXT("/p") ) ||
!_tcsicmp( argv[i], TEXT("-p") )) {
// assertion failure
NumPasses = argc > i ? _ttoi( argv[i+1] ) : 1;
if( !NumPasses ) return Usage( argv[0] );
i++;
} else {
if( foundFileArg ) return Usage( argv[0] );
foundFileArg = TRUE;
}
}
return 0;
}
i get assertion failure,
Please suggest where the problem might be and where to look. Is it some problem with _ttoi function i'm using when it fails,
if i have to allocate a buffer,
how can i resolve it
thanks
this line
NumPasses = argc > i ? _ttoi( argv[i+1] ) : 1;
should be
NumPasses = argc > 1+i ? _ttoi( argv[i+1] ) : 1;
Nick is right; don't forget that arrays start at zero in C/C++. If there are 5 elements, it means argv[0] to argv[4] are valid - not argv[5].

Roman to decimal conversion

What do you think about this code? Is it the best way? Any improvement?
Roman.h
#ifndef ROMAN_H
#define ROMAN_H
#include <string>
#include <map>
typedef unsigned long int UL_I;
typedef std::map< std::string, UL_I, std::less< std::string > > Map;
class Roman_Number
{
public:
//Constructor
Roman_Number( std::string );
void Convert_to_decimal();
UL_I get_Decimal() const;
std::string get_Roman() const;
private:
std::string s_roman_number;
UL_I d_number;
Map pairs;
Map pairs_substracting;
//Utilitaries functions
void _validate_();
void _initilize_pairs_()
{
pairs.insert( Map::value_type( "I", 1 ) );
pairs_substracting.insert( Map::value_type ( "IV", 4 ) );
pairs.insert( Map::value_type( "V", 5 ) );
pairs_substracting.insert( Map::value_type( "IX", 9 ) );
pairs.insert( Map::value_type( "X", 10 ) );
pairs_substracting.insert( Map::value_type( "XL", 40 ) );
pairs.insert( Map::value_type( "L", 50 ) );
pairs_substracting.insert( Map::value_type( "XC", 90 ) );
pairs.insert( Map::value_type( "C", 100 ) );
pairs_substracting.insert( Map::value_type( "CD", 400 ) );
pairs.insert( Map::value_type( "D", 500 ) );
pairs_substracting.insert( Map::value_type( "CM", 900 ) );
}
UL_I _recursive_convert( std::string );
};
#endif
Roman.cpp
#include <iostream>
#include "Roman.h"
void Roman_Number::_validate_()
{
std::cout << "Validating" << std::endl;
}
Roman_Number::Roman_Number(std::string r_number )
{
_initilize_pairs_();
s_roman_number = r_number;
d_number = 0;
}
void Roman_Number::Convert_to_decimal()
{
std::string s_aux = s_roman_number;
d_number = _recursive_convert( s_aux );
}
UL_I Roman_Number::_recursive_convert( std::string new_roman )
{
if( new_roman == "" )
return 0;
if( pairs_substracting.find( new_roman.substr( 0 , 2 ) ) != pairs_substracting.end() )
return pairs_substracting[new_roman.substr( 0, 2 )] +
_recursive_convert( new_roman.erase( 0, 2) );
else
return pairs[new_roman.substr( 0, 1 )] + _recursive_convert( new_roman.erase( 0, 1 ) );
}
UL_I Roman_Number::get_Decimal() const
{
return d_number;
}
std::string Roman_Number::get_Roman() const
{
return s_roman_number;
}
main.cpp
#include <iostream>
#include "Roman.h"
int main() {
Roman_Number R_N( "XIL" );
R_N.Convert_to_decimal();
std::cout << R_N.get_Decimal();
return 0;
}
How about this? http://codepad.org/mJ05BldC
#include <stdio.h>
int main( void ) {
const char* s = "MCDXLIV";
int x = 0; // result
int j,m=0; // max used digit
const char* p=s, *q; while(*p) ++p;
for( --p; p>=s; p-- ) for( q="IVXLCDM",j=0; *q; q++,j++ ) if( *p==*q )
x += ((j>=m)?m=j,1:-1) * (1+j%4/2*9) * (1+j/4*99) * (1+j%2*4);
printf( "s=%s x=%i\n", s, x );
}
Given
public static final String romanNums = "IVXLCDM";
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String input = console.nextLine();
int arabInt = 0;
for (int i = 0; i < romanNums.length(); i++) {
for (int j = 0; j < input.length(); j++) {
if (input.substring(j, j + 1).equals(romanNums.substring(i, i + 1))) {
arabInt += convertRomToNum(i);
if (j > 0 && romanNums.indexOf(input.substring(j, j + 1)) > romanNums.indexOf(input.substring(j - 1, j))) {
arabInt -= 2 * convertRomToNum(romanNums.indexOf(input.substring(j - 1, j)));
}
}
}
// AFTER OBSERVING PATTERN: 1, 5, 10, 50, 100, 500, 1000; AND ASSOCIATING INDEXES
// OF EACH ROMAN LETTER WITH CORRESPONDING NUMBER IN SEQUENCE ABOVE
public static int convertRomToNum(int i) {
int numBehindLetter = (int) (Math.pow(2, Math.floor(i / 2)) * Math.pow(5, Math.ceil(i / 2.)));
return numBehindLetter;
}
1 = 5^0 * 2^0; 5 = 5^1*2^0; 10 = 5^1*2^0; 50 = 5^2*2^1; 100 = 5^2*2^2; 500 = 5^3*2^2; 1000 = 5^3*2^3 and so on. This is why I have used 'floor' and 'ceil' functions.
Somewhere between convoluted and readable ...
int convRomanToInt(string roman) {
char[] symbol = { 'M', 'D', 'C', 'L', 'X','V','I' };
int[] weight = { 1000, 500, 100, 50, 10, 5 , 1 };
int res = 0, rom = 0, num = 0;
while (rom < roman.Length){
if (roman[rom] == symbol[num]){
res += weight[num];
rom++;
} else if (rom < roman.Length-1 && roman[rom+1] == symbol[num]){
res -= weight[(num&~1)+2];
rom++;
} else {
num++;
}
}
return res;
}

How to get the most current IHTMLDocument2 object from IE DOM

Currently, I use MSAA to get an IHTMLDocument2 object from a IE HWND. However, with some complicated web applications, this IHTMLDocument2 object may contain several IHTMLDocument2 objects, some of them are not belong to the current displaying page, but the previous page.
It seems to me, IE sometimes doesn't refesh its DOM object, but keep adding more IHTMLDocument2 object into its DOM. My question is how can I get the current displaying IHTMLDocument2 object from the DOM object.
Thanks in advance
Update
Hi Remy,
Thanks for your answer.
Yes, you are right, I do use frames to get to other IHTMLDocument2 objects. My understanding is that the IHTMLDocument2 object that I get from a HWND is the top object in its DOM. IE sometimes puts the prevous IHTMLDocument2 objects inside one of the frames as well.
Here is part of my code.
BOOL IESpy::GetHTMLText( CComPtr<IHTMLDocument2> spDoc, int tagNo, int schNo)
{
USES_CONVERSION;
HRESULT hr = NULL;
BOOL res = TRUE;
BOOL doneSearch = FALSE;
// Extract the source code of the document
if (spDoc) {
IHTMLFramesCollection2* pFrames = NULL;
if (hr = (spDoc->get_frames(&pFrames)) == S_OK){
LONG framesCount;
pFrames->get_length(&framesCount);
if (framesCount > 0) {
for( long i=0; i < framesCount; i++) {
VARIANT varIdx;
varIdx.vt=VT_I4;
VARIANT varResult;
varIdx.lVal=i;
VariantInit(&varResult);
hr = pFrames->item(&varIdx, &varResult);
if (SUCCEEDED(hr) && (varResult.vt == VT_DISPATCH)){
CComQIPtr<IHTMLWindow2> pFrameWnd;
CComQIPtr<IHTMLDocument2> pFrameDoc;
CComBSTR description=NULL;
pFrameWnd = varResult.pdispVal;
VariantClear(&varResult);
if (pFrameWnd == 0) {
continue;
}
hr = pFrameWnd->get_document(&pFrameDoc);
if (SUCCEEDED(hr) && pFrameDoc){
GetHTMLText( pFrameDoc, tagNo, schNo );
if ( m_foundText ) {
break;
}
} else if ( hr == E_ACCESSDENIED ) {
CComQIPtr<IWebBrowser2> spBrws = HtmlWindowToHtmlWebBrowser(pFrameWnd);
if ( spBrws != NULL) {
// Get the document object from the IWebBrowser2 object.
CComQIPtr<IDispatch> spDisp;
hr = spBrws->get_Document(&spDisp);
if ( hr == S_OK ) {
pFrameDoc = spDisp;
if ( pFrameDoc ) {
GetHTMLText( pFrameDoc, tagNo, schNo );
if ( m_foundText ) {
break;
}
}
}
}
}
}
}
}
pFrames->Release();
if ( !m_foundText ) {
res = ReadSearchText(spDoc, tagNo, schNo );
doneSearch = TRUE;
}
}
if ( !m_foundText && doneSearch == FALSE ) {
res = ReadSearchText(spDoc, tagNo, schNo );
}
}
return res;
}
BOOL IESpy::ReadSearchText(CComPtr<IHTMLDocument2> spDoc, int tagNo, int schNo )
{
USES_CONVERSION;
HRESULT hr = NULL;
BOOL found = FALSE;
IHTMLElementCollection *pAll;
hr = spDoc->get_all(&pAll);
if (FAILED(hr)) {
return FALSE;
}
long items;
IDispatch *ppvDisp;
IHTMLElement *ppvElement;
pAll->get_length(&items);
std::wstring foundText = L"";
for ( long j = 0; j < items; j++ ) {
VARIANT index;
index.vt = VT_I4;
index.lVal = j;
hr = pAll->item( index, index, &ppvDisp );
if (FAILED(hr)) {
return FALSE;
}
if ( ppvDisp ) {
ppvDisp->QueryInterface(IID_IHTMLElement, (void **)&ppvElement);
if ( ppvElement ) {
CComBSTR bstrTag;
ppvElement->get_tagName(&bstrTag);
wchar_t *wtemp = OLE2W(bstrTag);
if ( wtemp ) {
std::wstring text = ReadSearchText(ppvElement, wtemp, tagNo, schNo, found);
if ( !text.empty() ) {
if ( !foundText.empty() ) {
foundText += concat_string;
}
foundText += text;
}
ppvElement->Release();
if ( found ) {
BOOL stop = FALSE;
for ( size_t i = 0; i < m_tagName[tagNo]->size(); i++ ) {
if ( wcscmp(m_tagName[tagNo]->at(i).c_str(), L"HTML") == 0
|| wcscmp(m_tagName[tagNo]->at(i).c_str(), L"HEAD") == 0
|| wcscmp(m_tagName[tagNo]->at(i).c_str(), L"BODY") == 0 ) {
stop = TRUE;
break;
}
}
if ( stop ) {
break;
}
}
} else {
ppvElement->Release();
}
}
}
}
if ( !foundText.empty() ) {
if ( m_screenCompare ) {
// long timeStamp = GetHPTimeStamp(spDoc);
// m_temp_results[timeStamp] = foundText;
m_temp_results.push_back(foundText);
} else {
m_result += foundText;
m_result += L" ";
m_foundText = TRUE;
}
}
return TRUE;
}
An IHTMLDocument2 cannot contain other IHTMLDocument2 objects (unless they belong to frames on the page), and certainly not from previous pages. How are you determining that exactly? Can you show some code?