Categories
Geeky/Programming

VS2005 C++ Unit Tests – System.AccessViolationException: Attempted to read or write protected memory.

System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt..

If you have VS2005 C++ Unit Tests, written in managed C++ as they should be, and you are calling native code from them, and you see that error when running your unit tests – I have found it to mean that you are using insecure versions of methods (strcpy, etc). If you change the method calls to the secure versions, you should see your tests pass!

Categories
Geeky/Programming

VS2005 LNK1104 Error – cannot open file

If you are referncing another lib in a project and you goto build and get

fatal error LNK1104: cannot open file ‘C:MyProjectDebug.obj’

Do a double check in the project you are referencing configuration. If you have a space in the name (Say “Debug Test”) you might see this error and scratch your head. If the project you are referencing outputs to $(ConfigurationName), then the output directory will have a space. Seems that when you reference that project or lib, it doesn’t like it with a space in the path name, doh! 🙂

Categories
Geeky/Programming

HowTo: Make a Win32 DLL without MFC and ATL

Vs2005->New->Project

Win32->Win32 Project

On the Wizard, Application Settings, choose DLL radio box, hit finish.

This is all great, except when you build it, you just end up with a dll. How do you use the dll in another project?

Add a Module-Definition File (.def) – call it Export.def

next time you build, there will be a “.lib” file avail so you can link in the dll with another project.

You can add a EXPORTS section to export functions. The LIBRARY secion is added for you automatically. Have Fun with your new Win32 dll!

Categories
Geeky/Programming

VS2005 MFC Class Wizard Changes

If you ever used Visual Studio/C++ 6 (98), you would notice that the MFC Class Wizard allows you to set up messages as you create a class. Well, I’m not sure about VS2003, but VS2005, when you use the MFC Class Wizard, there are no options for setting up messages and events. Where did the options go?!?! Well, if you click on the class in class view, there are more little buttons on the properties window. If you click on the little icon next to the lightening bolt, you will see you can then set up messages for your class. Easy as 1-2-3!

Categories
Geeky/Programming

Static Code Analysis in C/C++

If you ever need to run static code analysis on C/C++ files, you can use Vs2005, but if you are in Vs2003, here is what you can do:

c:Program FilesMicrosoft Visual Studio 8VC>cl /analyze “C:MyCodeFile.c” > c:MyCodeFileAnalysis.txt

Found this on MSDN

Categories
Geeky/Programming

VS2005 – Browser Helper Object (BHO) Tutorial

I have been dabbling with BHO’s for some time, way back with VB6, then tried in .NET, and with C++ as well. There are so many cool things you can do with them. Anyways, most of the documentation out there is sparse and old. I told myself the next time I have to make one, I am going to document it. Well, here it is in all its glory. Sorry if the code formatting is wacked, but you get the picture. I don’t claim to be an expert, but this should work 🙂
just in case, I uploaded it in txt format for better reading here

How to Create a Browser Helper Object in Visual Studio 2005 with C++
———————————————————————
1) Open Visual Studio 2005
2) File->New->Project
3) Visual C++
4) ATL
5) ATL Project
6) Name is whatever you want for this example I use “Company.Browser.Helper” without the quotes

7) The ATL Project Wizard Screen will appear, Hit Finish
8) Visual Studio will load up your project.
9) Right Click on The Company.Browser.Helper project, Add->Class
10) select ATL Simple Object, and click the Add button
11) fill in the ShortName – “BrowserHelper” without the quotes, the rest of the fields should fill in, hit next
12) IMPORTANT: Under Support: Check all boxes (ISupportErrorInfo, Connection points, IObjectWithSite (IE object Support)
13) Click Finish

Now on to the better stuff,

————————————————————–

In visual studio, Solution Explorer, Resource Files, you will see BrowserHelper.rgs, open it and add this to the bottom
(replace the GUID with the GUID that you see at the top of the file like CLSID = s ‘{GUID}’) in the other script code
This will register the BHO with IE when the DLL gets registered


HKLM
{
SOFTWARE
{
Microsoft
{
Windows
{
CurrentVersion
{
Explorer
{
'Browser Helper Objects'
{
{GUID}
}
}
}
}
}
}
}

above where it says ‘Browser Helper’ – you can change those names to be more descriptive, that will show in IE add on manager

————————————————————–

————————————————————–

// in the Header Files -> stdafx.h, the bottom part of the file should look like this:

#include "resource.h"
#include
#include
#include

#define CAtlString CString

using namespace ATL;

--------------------------------------------------------------

//in Source Files-> BrowserHelper.cpp you need to include

#include

--------------------------------------------------------------

Then you need to implement methods listed here. You really shouldnt have to modify these

// this should be created by the wizard
STDMETHODIMP CBrowserHelper::InterfaceSupportsErrorInfo(REFIID riid)
{
static const IID* arr[] =
{
&IID_IBrowserHelper
};

for (int i=0; i FindConnectionPoint(DIID_DWebBrowserEvents2, &spCP);

if (FAILED(hr))
{
return hr;
}

// Subscribe the event handlers to the container
hr = spCP->Advise(reinterpret_cast(this), &m_dwCookie);

return hr;
}

STDMETHODIMP CBrowserHelper::IEUnAdvise(void)
{
HRESULT hr;
CComPtr spCP;

// Receives the connection point for WebBrowser events
hr = m_CPCptr->FindConnectionPoint(DIID_DWebBrowserEvents2, &spCP);

if (FAILED(hr))
{
return hr;
}

// Unsubscribe the event handlers to the container
hr = spCP->Unadvise(m_dwCookie);
return hr;
}

STDMETHODIMP CBrowserHelper::IEQuit(void)
{
return IEUnAdvise();
}

------------------------------------------------------------------------------------------

//then you need to implement the invoke method, as you can see i just care about the IEBeforeNaviate2() method
//so i commented the rest of the case statements out but left them in case i need them

STDMETHODIMP CBrowserHelper::Invoke(DISPID dispidMember, REFIID riid,
LCID lcid, WORD wFlags,
DISPPARAMS* pDispParams,
VARIANT* pvarResult,
EXCEPINFO* pExcepInfo, UINT* puArgErr)
{

if (!pDispParams)
{
return E_INVALIDARG;
}

switch(dispidMember)
{
case DISPID_BEFORENAVIGATE2: // Before Naigation
IEBeforeNavigate2(pDispParams);
break;

// case DISPID_COMMANDSTATECHANGE:// Command state change
// IECommandStateChange(pDispParams);
//break;

// case DISPID_DOCUMENTCOMPLETE: // Document completed
// IEDocumentComplete(pDispParams);
//break;

// case DISPID_DOWNLOADCOMPLETE: // Download completed
// IEDownloadComplete(pDispParams);
//break;

// case DISPID_NAVIGATECOMPLETE2: // Navigation completed
// IENavigateComplete2(pDispParams);
//break;

// case DISPID_NEWWINDOW2: // Open a new window
// IENewWindow2(pDispParams);
//break;

// case DISPID_PROGRESSCHANGE: // The progress status change
// IEProgressChange(pDispParams);
//break;

// case DISPID_STATUSTEXTCHANGE: // The status bar text change
// IEStatusTextChange(pDispParams);
//break;

// case DISPID_TITLECHANGE: // Title change
// IETitleChange(pDispParams);
//break;

// case DISPID_ONQUIT: // Quit
// IEQuit();
//break;
}
return S_OK;

}

------------------------------------------------------------------------------------------

//then implement BeforeNavigate2 - you can see the relevant code between the ***** that will
//check if IE is on google and redirect them to yahoo. You can add more code here like checking registry for a key,
//launching a process, etc, etc

void CBrowserHelper::IEBeforeNavigate2(DISPPARAMS* pDispParams)
{
CComQIPtr WebBrowser2Ptr;
CAtlString url;
VARIANT_BOOL* ptrBoolCancel;
VARTYPE vt;

// Check the type of IWebBrowser2
vt = pDispParams->rgvarg[6].vt;
if(vt == 0x0009)
{
WebBrowser2Ptr = pDispParams->rgvarg[6].pdispVal;
}
else
{
// Wrong type, return.
return;
}

// Check the first parameter type is VT_BYREF|VT_BOOL or not
vt = pDispParams->rgvarg[0].vt;
if(vt == 0x400B)
{
ptrBoolCancel = pDispParams->rgvarg[0].pboolVal;
}
else
{
// Wrong type, return.
return;
}

// Check the URL parameter type
vt = pDispParams->rgvarg[5].vt;
if(vt == 0x400C)
{
USES_CONVERSION;
url = OLE2T(pDispParams->rgvarg[5].pvarVal->bstrVal);
}
else
{
// Wrong type, return.
return;
}

// *********************************************************

// check for a given URL
if(url == _T("http://www.google.com/") || url == _T("http://www.google.com"))
{

BSTR newUrl = _T("http://www.yahoo.com/");

*ptrBoolCancel = TRUE;
WebBrowser2Ptr->Navigate(newUrl,NULL,NULL,NULL,NULL);

}

// ********************************************************
}

----------------------------

//you will need to wire these up in your header file, so in HEader Files->BrowserHelper.h it would look like this

----------------------------

// BrowserHelper.h : Declaration of the CBrowserHelper

#pragma once
#include "resource.h" // main symbols
#include "ExDisp.h"
#include "CompanyBrowserHelper.h"
#include "_IBrowserHelperEvents_CP.h"

#if defined(_WIN32_WCE) && !defined(_CE_DCOM) && !defined(_CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA)
#error "Single-threaded COM objects are not properly supported on Windows CE platform, such as the Windows Mobile platforms that do not include full DCOM support. Define _CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA to force ATL to support creating single-thread COM object's and allow use of it's single-threaded COM object implementations. The threading model in your rgs file was set to 'Free' as that is the only threading model supported in non DCOM Windows CE platforms."
#endif

// CBrowserHelper

class ATL_NO_VTABLE CBrowserHelper :
public CComObjectRootEx,
public CComCoClass,
public ISupportErrorInfo,
public IConnectionPointContainerImpl,
public CProxy_IBrowserHelperEvents,
public IObjectWithSiteImpl,
public IDispatchImpl
{
public:
CBrowserHelper()
{
}

DECLARE_REGISTRY_RESOURCEID(IDR_BROWSERHELPER)

BEGIN_COM_MAP(CBrowserHelper)
COM_INTERFACE_ENTRY(IBrowserHelper)
COM_INTERFACE_ENTRY(IDispatch)
COM_INTERFACE_ENTRY(ISupportErrorInfo)
COM_INTERFACE_ENTRY(IConnectionPointContainer)
COM_INTERFACE_ENTRY(IObjectWithSite)
END_COM_MAP()

BEGIN_CONNECTION_POINT_MAP(CBrowserHelper)
CONNECTION_POINT_ENTRY(__uuidof(_IBrowserHelperEvents))
END_CONNECTION_POINT_MAP()

public:

// ISupportsErrorInfo
STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid);

//
// IDispatch Methods
//
STDMETHOD(Invoke)(DISPID dispidMember,REFIID riid, LCID lcid,
WORD wFlags, DISPPARAMS* pdispparams,
VARIANT* pvarResult, EXCEPINFO* pexcepinfo,
UINT* puArgErr);

//
// IOleObjectWithSite Methods
//
STDMETHOD(SetSite)(IUnknown *pUnkSite);

DECLARE_PROTECT_FINAL_CONSTRUCT()

HRESULT FinalConstruct()
{
return S_OK;
}

void FinalRelease()
{
}

public:

private:
CComQIPtr m_CPCptr;
DWORD m_dwCookie; // Connection Token - used for
// Advise and Unadvise

enum ConnectType { Advise, Unadvise }; // What to do when managing
// the connection

STDMETHOD(IEAdvise)(void);
STDMETHOD(IEUnAdvise)(void);
STDMETHOD(IEQuit)(void);

void IEBeforeNavigate2(DISPPARAMS* pDispParams);

};

OBJECT_ENTRY_AUTO(__uuidof(BrowserHelper), CBrowserHelper)

----------------------------

And Finally,

To Test:

you shouldnt have to create or modify any more code, if you build it, you should get a dll

then to register with the system you need to call

regsvr32 DllName.dll

now open a browser and goto http://www.google.com and it will redirect to yahoo!

and if you look at the loaded add-ons, it should be in the list

close all your browsers

and to unregister

regsvr32 /u DllName.dll

open a browser and try google, it should work as normal

-------------------------------------------------------------

Categories
Geeky/Programming

SHGetFolderPath on Windows 98

SHGetFolderPath doesn’s seem to work on Windows 98. If you use it to try  to find like the “My Pictures” directory,  it will error out.  I have read that some versions of Win98 do work, depends on the version of shell32.dll (5 and greater). A workaround that you can use , which probably isn’t 100%  good, but works is looking for the My Pictures path in the registry  (HKEY_CURRENT_USERSoftwareMicrosoftWindowsCurrentVersionExplorerShell Folders). Just another quirky thing with the different Microsoft OS’s.

Categories
Geeky/Programming

strcpy vs. strncpy

strcpy – Copies the content pointed by src to dest stopping after the terminating null-character is copied.
dest should have enough memory space allocated to contain src string.

strncpy – Copies the first num characters of src to dest.
No null-character is implicitly appended to dest after copying process. So dest may not be null-terminated if no null-caracters are copied from src.
If num is greater than the length of src, dest is padded with zeros until num.

Now, maybe I just dont know, but why would you use strcpy when strncpy is available? I guess I really havent found a solid answer. I mean what were they thinking with strcpy? Were they just trying to create an easy way to have buffer overflows all over? (Same goes for strcat and strncat). I guess I am glad now to use C# and VB.net the majority of the time when you really don’t have to worry about this stuff. With C/C++ its all over the place, and you can tell, just look at all the buffer overflow vulnerabilites withing Microsoft products.

Categories
Geeky/Programming

Kill.exe and EnableDebugPriv()

The last few days, I have been looking into a solution to kill a process in c/c++ – but not just any process, a ScreenSaver running while the computer is locked. Most examples on MSDN and such terminiate processes by sending close messages to them, and 99% of the time that works. It even works for ScreenSavers that are running while the computer is locked. Thing is, I didnt want to bundle kill.exe that comes on the Windows NT Resource kit. Off to search google, pskill by sysinternals works too, but again with the bundling. Search the net some more, I found a link to the kill.exe source code from MSDN. The big difference in this code compared to all other kill examples, is this

//
// Obtain the ability to manipulate other processes
//
EnableDebugPriv();

That opened the door for the kill.exe to stop a process when the computer was locked 100% of the time. Im sure there is some long explination dealing with user mode and kernel mode code, maybe someone can comment on and shed some more light on the subject. I have attached the source code that I found here just in case the site it was on goes down. Well, in the end, we ended up getting the program to kill the process while the computer was locked, so it worked out well 🙂

Categories
Geeky/Programming

Visual C++ fatal error LNK1158 midl.exe

ok. Dang it I don’t like C++ and I was getting this error trying to compile a solution. Since searching in google doesnt give anything (do c++ developers use the internet yet?) I am posting this here for the next unlucky soul. What it means is that file is missing from an executable path or include path. What I did to fix was find midl.exe in another directory (C:Program FilesMicrosoft Visual Studio .NET 2003Common7ToolsBin to be exact) and then copied it to

C:program filesMicrosoft Visual Studio .NET 2003Vc7bin

and

C:program filesMicrosoft Visual Studio .NET 2003SDKv1.1Bin

and then my solution finally compiled. 🙂