Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
C

csrss

@csrss
About
Posts
146
Topics
43
Shares
0
Groups
0
Followers
0
Following
0

Posts

Recent Best Controversial

  • XMLHttpRequest (a)synchronous file upload
    C csrss

    Responding to my own question but it seems like I was messing around with this keyword in an inappropriate way. Correct code for sequential async file uploader goes like this:

    function XMLHttpUploader(place, targetPHP)
    {
    upload = function (currentArray, arrayTotalSize) {
    var currentFile = currentArray.shift();

        if (currentFile) {
            var xhr = new XMLHttpRequest();
            xhr.open('POST', targetPHP, true);
            xhr.setRequestHeader('UP-FILENAME', currentFile.name);
            xhr.setRequestHeader('UP-SIZE', currentFile.size);
            xhr.setRequestHeader('UP-TYPE', currentFile.type);
            xhr.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) {
                    var progressBar = document.querySelector('progress');
                    if (progressBar) {
                        progressBar.value = Math.round(((arrayTotalSize - currentArray.length) \* 100) / arrayTotalSize);
                    }
    
                    upload(currentArray, arrayTotalSize);
                }
            }
            xhr.onerror = function () {
                alert('File transfer failed!');
            }
            xhr.send(currentFile);
        }
        else {
            var progressBar = document.querySelector('progress');
            if (progressBar) {
                progressBar.value = 100;
                setTimeout("location.reload(true);", 2000);
            }
        }
    }
    
    // Function drop file
    this.drop = function(event) 
    {
        event.preventDefault();
    	var currentArray = new Array();
    	for (var i = 0; i < event.dataTransfer.files.length; i++) {
    	    currentArray.push(event.dataTransfer.files\[i\]);
    	}
    	upload(currentArray, currentArray.length);
    }
    
    // The inclusion of the event listeners (DragOver and drop)
    this.uploadPlace =  document.getElementById(place);
    this.uploadPlace.addEventListener("dragover", function(event)
    {
    	event.stopPropagation(); 
    	event.preventDefault();
    }, true);
    this.uploadPlace.addEventListener("drop", this.drop, false); 
    

    }

    011011010110000101100011011010000110100101101110 0110010101110011

    JavaScript tutorial javascript database sysadmin data-structures

  • XMLHttpRequest (a)synchronous file upload
    C csrss

    Hi guys. I do not know JS / AJAX / Web tech, I just need plain and simple mechanism for multiple files upload. Currently I have this (taken from the net actually):

    function uploader(place, targetPHP)
    {
    // Function drop file
    this.drop = function(event)
    {
    event.preventDefault();
    var dt = event.dataTransfer;
    var files = dt.files;

    	var progressBar = document.querySelector('progress');
    	for (var i = 0; i < files.length; i++) 
    	{
    		var file = files\[i\];
    	
    		xhr = new XMLHttpRequest();
    		xhr.open('POST', targetPHP, false);
    		xhr.setRequestHeader('UP-FILENAME', file.name);
    		xhr.setRequestHeader('UP-SIZE', file.size);
    		xhr.setRequestHeader('UP-TYPE', file.type);
    		xhr.onreadystatechange = function()
    		{
    			if(this.readyState == 4 && this.status == 200)
    			{
    				progressBar.value = Math.round((i \* 100) / files.length);
    			}
    		}
    		xhr.send(file); 
    	}
    	progressBar.value = 100;
    	setTimeout("location.reload(true);", 2000);
    }
    
    // The inclusion of the event listeners (DragOver and drop)
    this.uploadPlace =  document.getElementById(place);
    this.uploadPlace.addEventListener("dragover", function(event)
    {
    	event.stopPropagation(); 
    	event.preventDefault();
    }, true);
    this.uploadPlace.addEventListener("drop", this.drop, false); 
    

    }

    This thing uploading files synchronously one by one but it makes a browser, such as IE for example, freezes. I need to modify this script the way it will be doing same but asynchronously. So it will upload one file, then in onreadystatechange event it will trigger next file upload. This is because my server is a 2 threaded application, which processes XMLHttpRequest one by one. Basically, I got no idea how to modify this script that way because I do not know js / ajax at all. I was trying to collect files into an array, which was a class member, and then process them but uploader just stopped after first file upload. Thanks in advance.

    011011010110000101100011011010000110100101101110 0110010101110011

    JavaScript tutorial javascript database sysadmin data-structures

  • [C/C++] Parse multipart/form-data POST request in a small web server
    C csrss

    Figured it out - there is an error in my html form, it should be enctype, not type. Now I have a file content.

    011011010110000101100011011010000110100101101110 0110010101110011

    C / C++ / MFC question c++ html sysadmin agentic-ai

  • [C/C++] Parse multipart/form-data POST request in a small web server
    C csrss

    Hi there. I am looking for a simple, basic, preferable a C way of parsing multipart/form-data POST request from a client browser. So far I have a really simple web server, which reads web browser requests in a loop and prints them to to command prompt window:

    do
    {
    	len = recv(..., input\_buf, ...); 
    
    } 
        while (!strstr(input\_buf, "\\r\\n\\r\\n") && len > 0); 
    
    // Try to parse header and data
    char \* pch = nullptr, \*context = nullptr;
    pch = strtok\_s(input\_buf, "\\r\\n", &context);
    while (pch != nullptr)
    {
    	::puts(pch);
    	pch = strtok\_s (nullptr, "\\r\\n", &context);
    }
    

    When this web server starts, it just shows the following web form to the web browser:

    <form type=multipart/form-data method=post action=submit><input type=file multiple required /><input type=submit /></form>

    So far so good, ok, I connect to my server with firefox, select some test text file, which is a really small one - just a couple of bytes and hit an html form submit button. Server reads request and I have the following output in command prompt window:

    POST /submit HTTP/1.1
    Host: localhost:6666
    User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:24.0) Gecko/20100101 Firefox/
    24.0
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    Accept-Language: en-US,en;q=0.5
    Accept-Encoding: gzip, deflate
    Referer: http://localhost:6666/
    Connection: keep-alive
    Content-Type: application/x-www-form-urlencoded
    Content-Length: 0

    But the question is, how do I get file data? I was reading tons of online docs, when it says something about boundary strings - I have no idea what are boundary strings. I am just trying to figure out how to grab raw bytes file data. I cannot use any 3rd party libraries. And what concerns me, is that Content-Length is zero - seems like file was not transferred at all :( Can anyone help me with this? Thanks in advance :)

    011011010110000101100011011010000110100101101110 0110010101110011

    C / C++ / MFC question c++ html sysadmin agentic-ai

  • UDP sockets - not getting FD_READ after some time of activity on a socket
    C csrss

    Thanks for your suggestions :) Well, I knew about fd_write thing ;) Part about critical section got me thinking for sure - that is something I haven't considered in current implementation. Anyways, thanks very much, I need a moment to think about all this.

    011011010110000101100011011010000110100101101110 0110010101110011

    C / C++ / MFC graphics sysadmin question

  • UDP sockets - not getting FD_READ after some time of activity on a socket
    C csrss

    I think I am going to deal with it myself - code is too big and complicated to post it, or to even take one method from it - it is 1000+ lines custom network framework :( I am using UDP for consistency with discovery mechanisms, which I am implementing in app - it should do a lot of networking, pretty fast, without any user intervention - tcp will not allow me to, - it will force a solution where app will have to be configured by user and I cannot allow it to. I could do discovery only with UDP but I have written huge framework which actually implements TCP partially. Basically, I am not sure when FD_READ gets signaled? When there is data available or when WSARecvFrom can perform read? This would explain why it is not raised... I am going to deal with it on my own - it is too complicated :(

    011011010110000101100011011010000110100101101110 0110010101110011

    C / C++ / MFC graphics sysadmin question

  • UDP sockets - not getting FD_READ after some time of activity on a socket
    C csrss

    Hi there everyone. I have some pretty much basic UDP sockets scenario: my app requests data from server and receives requested data. There is a lot of data so there is a cancellation method as well. When I cancel data receiving and request data again, app not getting FD_READ events anymore. Strange thing is, it is not always the same - sometimes there are a couple of FD_READs, sometimes half of the data could be transmitted before it stops, sometimes - none. Code itself is basically the same as anywhere on the net and goes like this: 1. Before any receiving, check if FD_READ is set

    DWORD dwResult =
    ::WSAWaitForMultipleEvents(vecHandles.size(), &vecHandles[0], FALSE, dwTimeout, FALSE);

    - vecHandles is a vector of event handles, which includes my WSAEVENT for triggering cancellation. which is done like this:

    ::WSASetEvent(hEvent);

    So now ::WSAWaitForMultipleEvents will return with my event. 2. Check which event we got: if it is read event, then call recv.

    if( socket_event_read * pReadEvent = dynamic_cast(pSocketEvent) )
    {
    WSANETWORKEVENTS nt = { 0x00 };
    if( SOCKET_ERROR != ::WSAEnumNetworkEvents(pReadEvent->get_socket(), pSocketEvent, &nt) )
    {
    if( nt.lNetworkEvents & FD_READ && nt.iErrorCode[FD_READ_BIT] == false )
    {
    ::WSARecvFrom(...);
    }
    }
    }

    3. Handle data. That's it. It all works great if receiving is never cancelled. Otherwise it just stops at some point while waiting for multiple events (::WSAWaitForMultipleEvents) Again, what I mean is: I hit cancel button and

    ::WSASetEvent(hEvent);

    is called, that causes ::WSAWaitForMultipleEvents to return with my cancel event (WSAWaitForMultipleEvents is called in a loop for every incoming data chunk - each one is about 512kb). And then app just stops receiving - it leaves socket as it is, socket is not closed and still alive. Then I hit a button again for app to begin download data again and that is when app stops receiving packets because WSAWaitForMultipleEvents is waiting for fd_read which is never signaled. Then I hit cancel again, - this is handled properly and then again download data - this time data is downloading ok. This behavior occurs all the time. I am struggling with this for a couple of days now and got completely no idea what is going on, have searched all the net with no result. I have tried checking, when canc

    C / C++ / MFC graphics sysadmin question

  • Modeless Dialog box using win32 API only
    C csrss

    Hey, thanks for your reply. My problem was that i couldn't find a way to put the whole thing into nice C++ class of my own. But, problem was solved by using CreateDialogParam instead. So i can pass a pointer to the dialog class to a main message loop so i can call my own virtual methods inside children classes. Cheers.

    011011010110000101100011011010000110100101101110 0110010101110011

    C / C++ / MFC question json

  • Modeless Dialog box using win32 API only
    C csrss

    Is there any way of doing it? I am trying to write some simple class for showing modeless dialog box and just cannot understand what is wrong with it. While it is pretty easy with DialogBoxParam - there seems to be no way with CreateDialog. My goal is to pass somehow a pointer to a class to call my dlgProc. The way i am doing it with modal dlgbox:

    INT_PTR DoModal(UINT nResourceId)
    {
    ::InitCommonControls();
    return ::DialogBoxParam(::GetModuleHandle(NULL),
    MAKEINTRESOURCE(nResourceId),
    NULL, DlgProcModal, reinterpret_cast(this));
    }

    static INT_PTR __stdcall DlgProcModal(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
    {
    ....
    if( uMsg == WM_INITDIALOG )
    {
    if( !pWnd )
    {
    pWnd = reinterpret_cast(lParam);
    ::SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR)pWnd);
    pWnd->m_hWnd = hwndDlg;
    }
    }
    }

    The way i am trying to do it with modeless and it is just not working:

    INT_PTR DoModeless(UINT nResourceId)
    {
    ::InitCommonControls();
    if( m_hWnd = ::CreateDialog(::GetModuleHandle(NULL), MAKEINTRESOURCE(nResourceId), NULL, DlgProcModeless) )
    {
    m_bModeless = true;
    ::SetWindowLongPtr(m_hWnd, GWLP_USERDATA, (LONG_PTR)this);

    	MSG msg = { 0x00 };
    	while (::GetMessage(&msg, m\_hWnd, 0, 0)) 
    	{ 
    		if (!::IsDialogMessage(m\_hWnd, &msg))
    		{ 
    			::TranslateMessage(&msg); 
    			::DispatchMessage(&msg); 
    		}
    	}
    }
    ::DestroyWindow(m\_hWnd);
    return 0;
    

    }

    static INT_PTR __stdcall DlgProcModeless(
    HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam
    )
    {
    LONG_PTR lResult = ::GetWindowLongPtr(hwndDlg, GWLP_USERDATA);
    CBaseDlgWindow * pWnd = reinterpret_cast(lResult);
    ...
    }

    What am i doing wrong? Thanks in advance.

    011011010110000101100011011010000110100101101110 0110010101110011

    C / C++ / MFC question json

  • [mfc, custom control] Default Button
    C csrss

    Thank you so much!! :)

    011011010110000101100011011010000110100101101110 0110010101110011

    C / C++ / MFC help tutorial c++ graphics question

  • [mfc, custom control] Default Button
    C csrss

    It handles. But i need to catch somehow messages from other controls. Currently i am handling WM_MOUSEACTIVATE on a dialog window (this msg is posted when non-focused control gets focus, so basically when you click on any control on a dialog window , this dialog window gets this message) and then posting some dummy message to all child controls to make my controls redraw them selfs. But. There is one BUT. This message is posted before last control loses focus or something like that, anyways, only after second message my controls redraw them selfs correctly, so its like, "there is one click delay" - unacceptable in my case :(. So there should be some better way i dont know about

    011011010110000101100011011010000110100101101110 0110010101110011

    C / C++ / MFC help tutorial c++ graphics question

  • [mfc, custom control] Default Button
    C csrss

    i cannot see how this should solve my problem.

    011011010110000101100011011010000110100101101110 0110010101110011

    C / C++ / MFC help tutorial c++ graphics question

  • [mfc, custom control] Default Button
    C csrss

    Hi. I got my own custom button where i am doing all the painting myself. And now there is a problem: default button behavior. You know, like, these fancy regular windows buttons - when you click inside some Edit Box (let it be anywhere on the main app window) - button is drawn with blue shinning color. When you click on another button - that another button becomes default one. When you click inside some other edit box, again - this first button is drawn with a blue shinning color. The thing is : it is not an issue to check the style with:

    if( GetStyle() & BS_DEFPUSHBUTTON ) then...

    and do some additional drawing. The problem is: how to catch when a user clicked somewhere on another control which is not mine, which is regular windows edit box for example. Or another button which is just windows regular button? How do my button know when to draw some additional stuff to indicate it is a default button? Thanks

    011011010110000101100011011010000110100101101110 0110010101110011

    C / C++ / MFC help tutorial c++ graphics question

  • Drawing text issue
    C csrss

    Ahh, it was all about this MFC thing - sometimes you have to override some methods you got no idea about to make your control draw itself correctly. In this case it was:

    OnWindowPosChanged

    And just do nothing inside - static draws perfectly.

    011011010110000101100011011010000110100101101110 0110010101110011

    C / C++ / MFC graphics help c++

  • Drawing text issue
    C csrss

    The problem is i cannot use Gdiplus for drawing a string because my requirement is to draw the string with exact same font which windows OS uses. Gdiplus produce different font even if you do:

    HFONT hFOnt = ::GetStockObject(DEFAULT_GUI_FONT);

    and then create Gdiplus::Font from hFont. In theory you should have default font and maybe you do have, but DrawString draws text with a different font, not system default.

    011011010110000101100011011010000110100101101110 0110010101110011

    C / C++ / MFC graphics help c++

  • Drawing text issue
    C csrss

    Hi all. I got a huge problem while trying to draw a text with MFC. So, i got my custom class which extends CStatic. In OnPaint:

    CPaintDC dc(this);
    Gdiplus::Graphics * gfx = Gdiplus::Graphics::FromHDC(dc.GetSafeHdc());

    // then there a couple of things ... and then i am drawing a text like that (in another function which takes as IN parameter Gdiplus::Graphics, created in OnPaint):

    CDC * pDC = CDC::FromHandle(gfx->GetHDC());
    pDC->TextOut(0, 0, "my text");
    gfx->ReleaseHDC(pDC->GetSafeHdc());

    Simple. But every time OnPaint gets called - new text is drawn over old one, so it is getting bolder and bolder. And, it is not like the old one never erased, but it is erased only when there are about 5 same texts drawn over each one. Another thing, i've tried not to use Gdiplus at all - do everything only with CDC thing - same effect. Have used DrawText - same effect. Only with Gdiplus DrawString text is drawn correctly. But i need to draw it with Gdi32. Thanks.

    011011010110000101100011011010000110100101101110 0110010101110011

    C / C++ / MFC graphics help c++

  • IOCP again
    C csrss

    Thats basically doesnt matter, you can mix it. What you cannot is HeapAlloc and free or malloc and HeapFree for example. It seems to me that its kind of not possible to have memory allocations with IOCP. No matter what i do, app always crashes randomly. And there is always heap corruption. If there is static buffer - 1000 connections without a problem, if there is dynamic memory allocation - even one connection crashes.

    011011010110000101100011011010000110100101101110 0110010101110011

    C / C++ / MFC help debugging tutorial question lounge

  • IOCP again
    C csrss

    Here is a code, in short: 1. Extended overlapped:

    struct IOContext
    {
    WSAOVERLAPPED m_Overlapped;

    enum IOOperation
    {
    	IOAccept, 
    	IORead, 
    	IOWrite, 
    	IOConnect, 
    	IODisconnect, 
    	IODefault,
    	IOTerminate,
    	IOTerminateStopService
    };
    

    // some more data here
    //................
    IOOperation m_IOOperation;
    IOSocket * m_pSocket; // this is wrapper class for WSA functions
    LPBYTE m_pbIoRecvBuffer; // recv buffer
    DWORD m_cbIoRecvBuffer; // currently received bytes
    DWORD m_sbIoRecvBuffer; // bytes to receive

    LPBYTE			m\_pbIoSendBuffer;	// send buffer
    DWORD			m\_cbIoSendBuffer;	// currently sent bytes
    DWORD			m\_sbIoSendBuffer;	// bytes to send
    
    bool GrowRecvBuffer();
    bool FlushRecvBuffer();
    
    bool GrowSendBuffer();
    bool FlushSendBuffer();
    bool AllocSendBuffer(DWORD dwSize);
    

    }

    bool IOContext::GrowRecvBuffer()
    {
    m_sbIoRecvBuffer += 2048;
    m_pbIoRecvBuffer = (LPBYTE)::realloc(m_pbIoRecvBuffer,
    m_sbIoRecvBuffer);
    if(m_pbIoRecvBuffer == NULL)
    {
    return false;
    }
    return true;
    }

    bool IOContext::FlushRecvBuffer()
    {
    m_sbIoRecvBuffer = 0;
    m_cbIoRecvBuffer = 0;
    if(m_pbIoRecvBuffer)
    {
    ::free(m_pbIoRecvBuffer);
    m_pbIoRecvBuffer = NULL;
    }
    return true;
    }

    bool IOContext::GrowSendBuffer()
    {
    return true;
    }

    bool IOContext::FlushSendBuffer()
    {
    m_cbIoSendBuffer = 0;
    m_sbIoSendBuffer = 0;
    if(m_pbIoSendBuffer)
    {
    ::free(m_pbIoSendBuffer);
    m_pbIoSendBuffer = NULL;
    }
    return true;
    }

    bool IOContext::AllocSendBuffer(DWORD dwSize)
    {
    m_sbIoSendBuffer = dwSize;
    if(m_pbIoSendBuffer)
    {
    ::free(m_pbIoSendBuffer);
    m_pbIoSendBuffer = NULL;
    }
    m_pbIoSendBuffer = new BYTE[m_sbIoSendBuffer];
    return m_pbIoSendBuffer ? true : false;
    }

    2. Creating a worker thread, bind listen are just regular. Next is accept function, which is called when FD_ACCEPT event occurs:

    int myclass::StreamAccept()
    {
    int WSAStatus = 0;
    DWORD dwFlags = 0;

    IOContext \* pIoContextEx = new IOContext();
    
    try
    {
    ::RtlSecureZeroMemory(pIoContextEx, sizeof(IOContext));
    
    // associate our listen socket with IO port
    if(m\_bCorePortUpdated == false)
    {
    	this->m\_pCorePort->Update(m\_pCoreSocket->Socket(), (ULONG\_PTR)pIoContextEx);
    	m\_bCorePortUpdated = true;
    }
    
    // this will return accepted socket
    pIoContextEx->m\_pSocket = m\_pCoreSocket->WSAAccept(NULL, NULL);
    
    // associate new socket with completion port
    
    this->UpdateCorePort(pIoContextEx->m\_pSocket, pIoContextEx);
    
    // se
    
    C / C++ / MFC help debugging tutorial question lounge

  • IOCP again
    C csrss

    Hey Mark. The worst thing is, i am sure that i am doing everything the exact same way but something is always wrong. I can give you the code only if i could send it to you - it is a solution with 5 projects and there are a LOT of lines, if you could take a look at it and point out mistakes i would appreciate it so much!!! (because i desperately need help with this :( ), can i ask you for this? please? My email: info[at]machinized[dot]com or maybe you can post yours, then i can send you the code. I am in pain :(

    011011010110000101100011011010000110100101101110 0110010101110011

    C / C++ / MFC help debugging tutorial question lounge

  • IOCP again
    C csrss

    Hi guys. I am stuck again with IOCP again. The problem is that, i just cannot create more then one worker thread. If i'll create more then one worker thread, for example 10 and on the other side there are 10 client connections, everything crashes in a random places, or it crashes because buffer for WSARecv is not allocated while in debugger i can see perfectly allocated buffer, or it crashes because socket is invalid - i just dont get it. While it is only one thread - it is working perfectly, when there more threads, it becomes unstable, and when there are 10 or more, it crashes after 1 second. Is there some magic trick i am missing again? Thanks

    011011010110000101100011011010000110100101101110 0110010101110011

    C / C++ / MFC help debugging tutorial question lounge
  • Login

  • Don't have an account? Register

  • Login or register to search.
  • First post
    Last post
0
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups