I'm building a Windows 8.1 DirectX app and trying to load in an external to store level data.
The relevant code currently is (this method is called in the AssetHandler constructor):
void AssetHandler::LoadLevelsData()
{
unsigned int i = 0;
std::string lineData;
this->currentFile.open("Assets/reg.txt");
//Below statement here purely to check if the blasted thing is opening
if (this->currentFile.is_open())
{
i++;
}
while (std::getline(this->currentFile, lineData))
{
levels[i] = lineData;
i++;
}
currentFile.close();
}
The problem that i'm having is that the file does not appear to be opening. I have tried:
Using a full path
Opening the file in the initialisation list
A breakpoint shows that it is jumping over the if and while
I found some information saying that DirectX has constraints on working with external files but it did not specify exactly what these were.
The Item Type was set to 'Does not participate in build'. Setting this value to 'Text' solved the problem.
Related
Currently when an exception is thrown from within my Unity script while using my HoloLens the Debug Output in Visual Studio shows the stack trace without the line numbers.
How do I get the line numbers along with the stack trace? I'd be fine with it being logged somewhere else other than the Debug Output.
Here's some example output in Visual Studio:
Exception thrown: 'System.NullReferenceException' in Assembly-CSharp.dll
NullReferenceException: Object reference not set to an instance of an object.
at NewBehaviourScript.Update()
at NewBehaviourScript.$Invoke6Update(Int64 instance, Int64* args)
at UnityEngine.Internal.$MethodUtility.InvokeMethod(Int64 instance, Int64* args, IntPtr method)
(Filename: <Unknown> Line: 0)
And the corresponding Unity script (I made a Cube and attached a NewBehaviourScript component):
public class NewBehaviourScript : MonoBehaviour {
// Update is called once per frame
void Update ()
{
object a = null;
a.GetType();
}
}
I tried changing the build from Release to Debug doesn't give the line numbers.
I tried googling, and it looks like it's not showing the line numbers for others, as well: http://answers.unity3d.com/questions/1315985/null-reference-in-line-0.html
I tried asking on Microsoft's forums, but didn't receive any useful replies.
I don't think you would get the line number since it does not exist anymore. You get it in Unity editor because you are not running a full build of the application so Unity still has access to the non-compiled code. When you run on the device, it sends debug commands to the VS console about the printing and the errors but all the code is binary at that point, so there is no reason nor possibility to provide a line number.
Actually this is not specific to Hololens, but you would get the same in Android or iOS. Once build, the code is no longer the same, it does not even match one to one as the compiler performs optimizations.
What you can do is placed Debug commands to see where it happens.
public class NewBehaviourScript : MonoBehaviour {
// Update is called once per frame
void Update ()
{
object a = null;
#if DEBUG
if(a == null)
{
Debug.Log("[NewBehaviourScript] Running update with null a object");
}
#endif
a.GetType();
Debug.Log("[NewBeahviourScript] if this line prints, method did not crash");
}
}
In this example, you can use the DEBUG macros if you would have code running only for debug purpose. This way you can easily exclude it on export. The second call for Debug is not required in the macro since the build process will discard it when you set the build to Release or Master.
When using 'Load-Time Dynamic Linking'(using an import library .lib in compilation that loads a dll when the module is loaded) in a Win32 application, is it possible to affect the search order?
The goal is to have a library loaded using the normal search order, with a back-up path if one is not found on the normal path.
Example: foo.lib is linked in the project. At load time:
If foo.dll is present in the System path or any of the other paths mentioned in Dynamic-Link Library Search Order then it will be loaded.
Else mySpecifiedPath/foo.dll will be loaded.
Clarification: The back-up dll should only be loaded if no version of the dll is found in the standard LoadLibrary search paths.
Leaving the old answer at the bottom and adding a new one at the top:
The combination of delay-loading and the delay-load Failure Hook as described at provides a nice way to handle this.
Register the failure hook that loads the back-up dll before using any symbol from the library.
#include <Windows.h>
#include "foo.h"
#include <delayimp.h>
//access to set the failure hook
ExternC PfnDliHook __pfnDliFailureHook2;
const char* dllName = "foo.dll";
const char* dllBackupPath = "pathToBackup\\foo.dll";
FARPROC WINAPI DelayLoadHook(unsigned dliNotify, PDelayLoadInfo pdli)
{
//if the failure was failure to load the designated dll
if (dliNotify == dliFailLoadLib &&
strcmp(dllName, pdli->szDll) == 0 &&
pdli->dwLastError == ERROR_MOD_NOT_FOUND)
{
printf("loading back-up dll\n");
//return the successfully loaded back-up lib,
//or 0, the LoadLibrary fails here
HMODULE lib = LoadLibraryA(dllBackupPath);
return (FARPROC)lib;
}
return 0;
}
int main()
{
//set the Failure Hook
__pfnDliFailureHook2 = &DelayLoadHook;
//when this function is called the library will be loaded
//from standard paths. If it is not found the Failure Hook
//set above will be called.
int test = ::intReturningFuncFromFooDll();
printf("%d", test);
getchar();
return 0;
}
===========old answer below==============
Looks like what I was looking for is delay-loading, as mentioned in the comment by IInspectable. I found information regarding this:
Linker Support for Delay-Loaded DLLs
Here is some code demonstrating the usage I mentioned in the original post:
//load the dll using the normal search
HMODULE lib = LoadLibrary( L"foo.dll" );
//if unsuccessful, try a specified path
if (lib == NULL)
{
LoadLibrary( L"mySpecifiedPath/foo.dll" );
}
if (lib == NULL)
{
//make sure that the library is not used,
//or exit the application, as it was not found
}
Thanks for the help!
edit to old answer: This dynamic loading would be used before any symbol from the library is used. The delay loaded fills out the symbol addresses using the module loaded here the first time a symbol from the library is accessed.
Looking at the Dynamic-Link Library Search Order documentation, it should be obvious, that the final location searched is the PATH environment variable. Applying that knowledge, the easiest solution that meets all your requirements is to append the backup location to the PATH variable.
This could be done in two ways:
An external launcher: The CreateProcess API call allows an application, to pass a custom environment to the new process through the lpEnvironment argument. The current process' environment block can be queried by calling GetEnvironmentStrings.
Enable delay-loading of the desired DLL(s) using the /DELAYLOAD linker option, and modify the process' environment at application startup. After retrieving the PATH environment variable (using GetEnvironmentVariable), it can be modified and updated in the environment block by calling SetEnvironmentVariable.
I have an application (written in C++ with MFC, but I don't think that that's particularly relevant) that embeds the Internet Explorer ActiveX WebBrowser control for the purpose of showing some HTML pages. One requirement has always been to use the application's font name and size settings as the default settings for the HTML, rather than Internet Exporer's defaults.
To achieve this, the application implements the IDocHostUIHandler2 COM interface, which it passes to the WebBrowser control. This causes the control to call the application's implementation of GetOptionKeyPath, which lets the application set the registry location that the WebBrowser control gets its settings from. Armed with Sysinternals' tools to see which keys IE uses to find the font name and size, this has been sufficient to do what I need.
However, the appeareance of Internet Explorer 9 has come as a nasty surprise: on all machines that I've tested with that have IE9 installed, the WebBrowser control uses its own settings, ignoring the registry location from the application. Testing with a debugger shows that the WebBrowser control never calls the provided GetOptionKeyPath.
A bit more experimentation shows that the IE9 WebBrowser control is calling the similar (but not identical) GetOverrideKeyPath method: this allegedly provides a way to override IE settings, while falling back to IE's actual settings if nothing is found in the relevant part of the registry. Unfortunately this has two problems: 1) It's not quite what I want, and 2) IE9 doesn't always check under the GetOverrideKeyPath registry location before going to the IE default registry settings.
Looking at the GetOptionKeyPath MSDN page there are a few complaints along similar lines, but no solutions. Has anyone found a clean way to persuade the WebBrowser control to revert to the pre-IE9 behaviour of actually calling GetOptionKeyPath as documented?
I've come up with a hack to solve this problem, but I should warn you: it's not pretty. Stop reading now if you've easily offended ...
Since there seems to be no way of making IE9 use the IDocHostUIHandler::GetOptionKeyPath() method, I used SysInternals' tools to see which IE9 DLLs accessed the relevant parts of the registry to load the IE9 settings. This revealed the only culprits as "mshtml.dll" and "iertutil.dll", both of which call RegOpenKeyExW().
The plan was then to load these DLLs before initializing the WebBrowser control, and patch them so that calls are redirected to my code, where I can lie about what registry key I've opened, using dbghelp.dll. So, to start, before initializing the WebBrowser control:
if (theApp.GetIEVersion() >= 9.0)
{
HMODULE advadi = ::LoadLibrary("advapi32.dll");
HMODULE mshtml = ::LoadLibrary("mshtml.dll");
HookApiFunction(mshtml,advadi,"advapi32.dll","RegOpenKeyExW",(PROC)HookRegOpenKeyExW);
HMODULE iertutil = ::LoadLibrary("iertutil.dll");
HookApiFunction(iertutil,advadi,"advapi32.dll","RegOpenKeyExW",(PROC)HookRegOpenKeyExW);
}
And now, the code that does the evil work of scanning the DLLs import address tables, and patching the requested function (error handling omitted to keep the code size down):
void HookApiFunction(HMODULE callingDll, HMODULE calledDll, const char* calledDllName, const char* functionName, PROC newFunction)
{
// Get the pointer to the 'real' function
PROC realFunction = ::GetProcAddress(calledDll,functionName);
// Get the import section of the DLL, using dbghelp.dll's ImageDirectoryEntryToData()
ULONG sz;
PIMAGE_IMPORT_DESCRIPTOR import = (PIMAGE_IMPORT_DESCRIPTOR)
ImageDirectoryEntryToData(callingDll,TRUE,IMAGE_DIRECTORY_ENTRY_IMPORT,&sz);
// Find the import section matching the named DLL
while (import->Name)
{
PSTR dllName = (PSTR)((PBYTE)callingDll + import->Name);
{
if (stricmp(dllName,calledDllName) == 0)
break;
}
import++;
}
if (import->Name == NULL)
return;
// Scan the IAT for this DLL
PIMAGE_THUNK_DATA thunk = (PIMAGE_THUNK_DATA)((PBYTE)callingDll + import->FirstThunk);
while (thunk->u1.Function)
{
PROC* function = (PROC*)&(thunk->u1.Function);
if (*function == realFunction)
{
// Make the function pointer writable and hook the function
MEMORY_BASIC_INFORMATION mbi;
::VirtualQuery(function,&mbi,sizeof mbi);
if (::VirtualProtect(mbi.BaseAddress,mbi.RegionSize,PAGE_READWRITE,&mbi.Protect))
{
*function = newFunction;
DWORD protect;
::VirtualProtect(mbi.BaseAddress,mbi.RegionSize,mbi.Protect,&protect);
return;
}
}
thunk++;
}
Finally, the function that I have patched the DLLs to call in my code, in place of RegOpenKeyExW():
LONG WINAPI HookRegOpenKeyExW(HKEY hKey, LPCWSTR lpSubKey, DWORD ulOptions, REGSAM samDesired, PHKEY phkResult)
{
static const wchar_t* ieKey = L"Software\\Microsoft\\Internet Explorer";
// Never redirect any of the FeatureControl settings
if (wcsstr(lpSubKey,L"FeatureControl") != NULL)
return ::RegOpenKeyExW(hKey,lpSubKey,ulOptions,samDesired,phkResult);
if (wcsnicmp(lpSubKey,ieKey,wcslen(ieKey)) == 0)
{
// Redirect the IE settings to our registry key
CStringW newSubKey(m_registryPath);
newSubKey.Append(lpSubKey+wcslen(ieKey));
return ::RegOpenKeyExW(hKey,newSubKey,ulOptions,samDesired,phkResult);
}
else
return ::RegOpenKeyExW(hKey,lpSubKey,ulOptions,samDesired,phkResult);
}
Amazingly enough, this horrible hack actually works. But please, Microsoft, if you're listening, please fix this properly in IE10.
I've got a visual studio addin written by developer who is no longer at the company and have no idea how to debug it. But I want to add a feature so it can recurse into solution folders.
Sounds simple but I'm not sure the api allows testing for this?
Well there's got to be a way because AnkhSVN and VisualSVN work fine with Solution Folders.
StackOverflow I'm reaching out for some help on this issue.
Thanks
Notes
-We are using solution folders to hide "Dependency Projects" which are basically a list of project references that we probably don't care about in the particular solution and want to hide by default.
public class Connect : IDTExtensibility2, IDTCommandTarget
{
public void GetProjectLocations(DTE2 dte)
{
UIHierarchy UIH = dte.ToolWindows.SolutionExplorer;
try
{
UIHierarchyItem UIHItemd = UIH.UIHierarchyItems.Item(1);
}
catch (Exception E)
{
Debug.Write(E);
}
UIHierarchyItem UIHItem = UIH.UIHierarchyItems.Item(1);//this looks suspect to me
// Iterate through first level nodes.
for (int i = 1; i <= UIHItem.UIHierarchyItems.Count; i++)
{
Project TempGeneralProjObj = dte.Solution.Item(i);
if (TempGeneralProjObj.Kind == PrjKind.prjKindCSharpProject)
{
}
}
}
}
So far from my tests it appears that solution folders will cast to type Project surprisingly and once that is done the Project.ProjectItems property will hold a list of Projects that may exists underneath that folder. So in short, this is one way to at least get information about how things are structured. The problem however is that each ProjectItem located underneath a solution folder appears to cast find to type ProjectItem but doesn't seem to be able to be cast to a Project.
This is how I'm currently detecting a solution folder in my loop.
if(project.Kind == "{66A26720-8FB5-11D2-AA7E-00C04F688DDE}")
{
// TODO: Do your thing
}
This has also been frustrating me and I've also noticed a bug in how ActiveReports handles solution folders as well which is related to this same issue.
UPDATE!
Ok so I found the solution but I can't claim it 100% because I found most of it at Macaw's Blog.
So it appears that my original findings were right on however in order to get the actual project type for each ProjectItem under the solution item you need to look under the ProjectItem.SubProject property.
Now Macaw takes a recursive approach to walking the project structure which I think I would also normally recommend however in my case I wanted a single method implementation to simply log out an XML representation of the project for simple research purposes so I ended up using a Stack implementation. For reference you can find my code below which is successfully handling at least one level of solution folders full of projects only and no other specialty solution items.
XElement rootNode = new XElement("Solution");
rootNode.Add(new XAttribute("Name", _applicationObject.Solution.FullName));
Stack<Project> projectStack =
new Stack<Project>(_applicationObject.Solution.Projects.Cast<Project>());
while(projectStack.Count > 0)
{
var project = (Project)projectStack.Pop();
var solutionItemName = "Project";
if(project.Kind == "{66A26720-8FB5-11D2-AA7E-00C04F688DDE}")
{
foreach(ProjectItem innerProject in project.ProjectItems)
{
if(innerProject.SubProject != null)
{
projectStack.Push(innerProject.SubProject);
}
}
solutionItemName = "Folder";
}
var projectNode = new XElement(
solutionItemName,
new XAttribute("Name", project.Name),
new XAttribute("Kind", project.Kind)
);
rootNode.Add(projectNode);
foreach(ProjectItem item in project.ProjectItems)
{
var itemNode = new XElement("Item", new XAttribute("Name", item.Name));
projectNode.Add(itemNode);
if(item.Properties == null)
{
continue;
}
foreach(Property property in item.Properties)
{
var propertyNode = new XElement(property.Name, property.Value);
itemNode.Add(propertyNode);
}
}
}
By the fact of this post and by apparent bugs in other Add-ins it is apparent that this isn't the most intuitive design but thats what we have to live with.
To debug a Visual Studio add-in, load the source code into a copy of visual studio that is not running the add-in. Then, configure the project to start a second copy of visual studio when you "run" the project, that second copy will then run with the first able to breakpoint and debug it.
Make sure you have a batch file (or equivalent) to clean up, so that you can always get back to running VS without the plugin.
Useful resources ...
How to debug a Visual Studio .NET 2005 Add-In
Walkthrough: Debugging an Add-in Project
I'm using Microsoft's DSOFramer control to allow me to embed an Excel file in my dialog so the user can choose his sheet, then select his range of cells; it's used with an import button on my dialog.
The problem is that when I call the DSOFramer's OPEN function, if I have Excel open in another window, it closes the Excel document (but leaves Excel running). If the document it tries to close has unsaved data, I get a dialog boxclosing Excel doc in another window. If unsaved data in file, dsoframer fails to open with a messagebox: Attempt to access invalid address.
I built the source, and stepped through, and its making a call in its CDsoDocObject::CreateFromFile function, calling BindToObject on an object of class IMoniker. The HR is 0x8001010a The message filter indicated that the application is busy. On that failure, it tries to InstantiateDocObjectServer by classid of CLSID Microsoft Excel Worksheet... this fails with an HRESULT of 0x80040154 Class not registered. The InstantiateDocObjectServer just calls CoCreateInstance on the classid, first with CLSCTX_LOCAL_SERVER, then (if that fails) with CLSCTX_INPROC_SERVER.
I know DSOFramer is a popular sample project for embedding Office apps in various dialog and forms. I'm hoping someone else has had this problem and might have some insight on how I can solve this. I really don't want it to close any other open Excel documents, and I really don't want it to error-out if it can't close the document due to unsaved data.
Update 1: I've tried changing the classid that's passed in to Excel.Application (I know that class will resolve), but that didn't work. In CDsoDocObject, it tries to open key HKEY_CLASSES_ROOT\CLSID\{00024500-0000-0000-C000-000000000046}\DocObject, but fails. I've visually confirmed that the key is not present in my registry; The key is present for the guide, but there's no DocObject subkey. It then produces an error message box: The associated COM server does not support ActiveX document embedding. I get similar (different key, of course) results when I try to use the Excel.Workbook programid.
Update 2: I tried starting a 2nd instance of Excel, hoping that my automation would bind to it (being the most recently invoked) instead of the problem Excel instance, but it didn't seem to do that. Results were the same. My problem seems to have boiled down to this: I'm calling the BindToObject on an object of class IMoniker, and receiving 0x8001010A (RPC_E_SERVERCALL_RETRYLATER) The message filter indicated that the application is busy. I've tried playing with the flags passed to the BindToObject (via the SetBindOptions), but nothing seems to make any difference.
Update 3: It first tries to bind using an IMoniker class. If that fails, it calls CoCreateInstance for the clsid as a fallback method. This may work for other MS Office objects, but when it's Excel, the class is for the Worksheet. I modified the sample to CoCreateInstance _Application, then got the workbooks, then called the Workbooks::Open for the target file, which returns a Worksheet object. I then returned that pointer and merged back with the original sample code path. All working now.
#Jinjin
You can use the #import directive to import your Excel's OLB file. this should generate (and automatically include an Excel .tlh file which contains the structures for _Application (and the rest you need)). Ideally, you should find an OLB file that matches the earliest Excel version that you wish to support. The one on your local system is probably in c:\Program Files\Microsoft Office\Office12 (presuming you have Office 2007 installed). It may be named Excel.olb, or XL5EN32.OLB (different, obviously if you haven't installed the US English verion of Excel.
So, copy the .olb file to your project source directory, then at the top of the source file, add a line for #import "XL5EN32.olb".
Yes, opens older versions. Best way to guarantee that this will be the case is to find an OLB file (mentioned in item 1 above) that is from an installation of Excel that is the earliest version you wish to support. I use an Excel9.olb from Office 2000. Works fine with my testing of Excel versions all the way to the latest from Office 2007.
Yes, you should use dsoframer normally after making these changes.
I'm afraid I probably can't do that due to restrictions of my employer. However, if you take the "stock" dsoframer project, make the changes described in part 1 of this post, and the changes I described in my earlier post, you have pretty much recreated exactly what I have.
#Jinjin: did you put the import statement (#import "XL5EN32.olb") in the cpp file where you are using the Excel::_Application? If not, do that... can't just add it to the project. If you have already done that, try also adding this statement to the cpp file where you are using those mappings #import "Debug\XL5EN32.tlh". The tlh file is a header that is generated by running the #import; you should find it in your Debug directory (presuming you're performing a Debug build).
Renaming _Application to Application (and the others) is not the right way to go. The _Application structure is the one that has the mappings. That is why you are not finding the app->get_Workbooks.
What file are you looking in that you are finding Application but not _Application?
Assuming you are using the DSOFRAMER project, you need to add this code to dsofdocobj.cpp in the CreateFromFile function, at around line 348:
CLSID clsidExcelWS;
hr = CLSIDFromProgID(OLESTR("Excel.Sheet"),clsidExcelWS);
if (FAILED(hr)) return hr;
if (clsid == clsidExcelWS)
{
hr = InstantiateAndLoadExcel(pwszFile, &pole);
if (FAILED(hr)) return hr;
}
else
{
<the IMoniker::BindToObject call and it's failure handling from the "stock" sample goes here>
}
Then, define the following new member function in CDsoDocObject:
////////////////////////////////////////////////////////////////////////
// CDsoDocObject::InstantiateAndLoadExcel (protected)
//
// Create an instance of Excel and load the target file into its worksheet
//
STDMETHODIMP CDsoDocObject::InstantiateAndLoadExcel(LPWSTR pwszFile, IOleObject **ppole)
{
IUnknown *punkApp=NULL;
Excel::_Application *app=NULL;
Excel::Workbooks *wbList=NULL;
Excel::_Workbook *wb;
CLSID clsidExcel;
HRESULT hr = CLSIDFromProgID(OLESTR("Excel.Application"), &clsidExcel);
if (FAILED(hr))
return hr;
hr = CoCreateInstance(clsidExcel, NULL, CLSCTX_LOCAL_SERVER, IID_IUnknown, (void**)&punkApp);
if (SUCCEEDED(hr))
{
hr = punkApp->QueryInterface(__uuidof(Excel::_Application),(LPVOID *)&app);
if (SUCCEEDED(hr))
{
hr = app->get_Workbooks(&wbList);
VARIANT vNoParam;
VariantInit(&vNoParam);
V_VT(&vNoParam) = VT_ERROR;
V_ERROR(&vNoParam) = DISP_E_PARAMNOTFOUND;
VARIANT vReadOnly;
VariantInit(&vReadOnly);
V_VT(&vReadOnly) = VT_BOOL;
V_BOOL(&vReadOnly) = VARIANT_TRUE;
BSTR bstrFilename = SysAllocString(pwszFile);
hr = wbList->Open(bstrFilename, vNoParam,vNoParam,vNoParam,vNoParam,vReadOnly,vNoParam,vNoParam,vNoParam,vNoParam,vNoParam,vNoParam,vNoParam,0,&wb);
if (SUCCEEDED(hr))
hr = wb->QueryInterface(IID_IOleObject, (void**)ppole);
VariantClear(&vReadOnly);
VariantClear(&vNoParam);
SysFreeString(bstrFilename);
}
}
if (wb != NULL) wb->Release();
if (wbList != NULL) wbList->Release();
if (app != NULL) app->Release();
if (punkApp != NULL) punkApp->Release();
return hr;
}