Unity not resolving registered dependency.. even though it really is registered - dependency-injection

This is driving me nuts...
Two assemblies/projects in play:
An Infrastructure project, which has an interface in it:
IDtoMapping<in TDto, out TDomain>
And an app project, referencing Infx, with an implementation:
PatientMapping : IPatientMapping
...and a marker interface, just to be clear:
public interface IPatientMapping : IDtoMapping<PatientDTO, Patient> {}
When the app boots, this gets run:
_container.RegisterType<IPatientMapping, PatientMapping> ( new ContainerControlledLifetimeManager () );
This happens in the app project, through a system-wide bootstrapping process.
(Immediately after this line runs, (through a watch), I can successfully resolve it.)
Finally, we try to resolve it (in a WCF service, in the app projec)
public PatientService (
IPatientRepository patientRepository,
ISessionSource session,
IPatientMapping patientDtoToDomainMapper )
{
.. and it fails. With the ResolutionFailedException "Cannot instantiate an interface, etc.." I've put break points at the .Resolve call, the registration, etc.. everything is getting hit as expected. But when the app tries to Resolve/BuildUp the WCF Service, Unity can't resolve the IPatientMapping parameter... it's like it forgot.
I'm at a loss.. I upgraded to Unity 2.0, added that intermediate marker interface, removed the generic interface and just used the vanilla one.. all to no avail.
Other dependencies in the system resolve just fine, including the other parameters on that same WCF constructor.
The only thing my gut is telling me is could it have something to do with the assemblies? That the .Resolve call is happening in the Infx project, but the implementation actually lives in the app-project? At runtime, all assemblies are loaded, so it shouldn't really matter, right?
Thanks for any ideas!

Related

Attempted an Unsupported Operation Using Serial port

I am recompiling an application from Visual C++ 6.0 in Visual Studio 2015. It is using Mscomm as serial communication library. Everything gets compiled fine but when I run the program, I get "Attempted an Unsupported Operation" twice. Upon debugging I found out the culprit is the following snippet:
void CFFLSView::DoDataExchange(CDataExchange* pDX)
{
CFormView::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CFFLSView)
DDX_Control(pDX, IDC_MSCOMM1, m_comm);
DDX_Control(pDX, IDC_MSCOMM2, m_comm2);
//}}AFX_DATA_MAP
}
This calls m_comm and m_comm2 to be open COM1 and COM2. I don't have the equipment connected to my computer now, and I will have to test the compiled software at site tomorrow. I suspect that because nothing is connected to COM1 and COM2, the program cannot open port and returns that error but I am not sure that is the case, getting in the site is very difficult and I only have one opportunity to go in and test the software there. I want to make sure that this error is only given because nothing is connected to COM1 and COM2 and not any other problem. I appreciate your comments and thoughts on this. If it helps, the DDX_Control function calls the following function in debug mode:
void CMSComm::SetPortOpen(BOOL bNewValue)
{
static BYTE parms[] =
VTS_BOOL;
InvokeHelper(0x14, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms,
bNewValue);
}
which is supposed to open the port.

Reset app state between InstrumentationTestCase runs

One of my QA engineers is supporting an app with a fairly large codebase and a lot of different SharedPreferences files. He came to me the other day asking how to reset the application state between test runs, as if it had been uninstalled-reinstalled.
It doesn't look like that's supported by Espresso (which he is using) nor by the Android test framework natively, so I'm not sure what to tell him. Having a native method to clear all the different SharedPreferences files would be a pretty brittle solution.
How can one reset the application state during instrumentation?
Current espresso doesn't provide any mechanism to reset application state. But for each aspect (pref, db, files, permissions) exist a solution.
Initial you must avoid that espresso starts your activity automatically so you have enough time to reset.
#Rule
public ActivityTestRule<Activity> activityTestRule = new ActivityTestRule<>(Activity.class, false, false);
And later start your activity with
activityTestRule.launchActivity(null)
For reseting preferences you can use following snippet (before starting your activity)
File root = InstrumentationRegistry.getTargetContext().getFilesDir().getParentFile();
String[] sharedPreferencesFileNames = new File(root, "shared_prefs").list();
for (String fileName : sharedPreferencesFileNames) {
InstrumentationRegistry.getTargetContext().getSharedPreferences(fileName.replace(".xml", ""), Context.MODE_PRIVATE).edit().clear().commit();
}
You can reset preferences after starting your activity too. But then the activity may have already read the preferences.
Your application class is only started once and already started before you can reset preferences.
I have started to write an library which should make testing more simple with espresso and uiautomator. This includes tooling for reseting application data. https://github.com/nenick/espresso-macchiato See for example EspAppDataTool with the methods for clearing preferences, databases, cached files and stored files.
Improving on #nenick's solution, encapsulate the state clearing behavior in a custom ActivityTestRule. If you do this, you can allow the test to continue to launch the activity automatically without intervention from you. With a custom ActivityTestRule, the activity is already in the desired state when it launches for the test.
Rules are particularly useful because they're not tied to any specific test class, so can be easily reused within any test class or any project.
Below is one I implemented to ensure that the app is signed out when the activity launches, per test. Some tests, when they failed, were leaving the app in a signed in state. This would then cause later tests to also fail because the later ones assumed they would need to sign in, but the app would already be signed in.
public class SignedOutActivityTestRule<T extends Activity> extends ActivityTestRule<T> {
public SignedOutActivityTestRule(Class<T> activityClass) {
super(activityClass);
}
#Override
protected void beforeActivityLaunched() {
super.beforeActivityLaunched();
InstrumentationRegistry.getTargetContext()
.getSharedPreferences(
Authentication.SHARED_PREFERENCES_NAME,
Context.MODE_PRIVATE)
.edit()
.remove(Authentication.KEY_SECRET)
.remove(Authentication.KEY_USER_ID)
.apply();
}
}
you can try add this to gradle:
android {
...
defaultConfig {
...
testInstrumentationRunnerArguments clearPackageData: 'true'
}
}
refer to https://developer.android.com/training/testing/junit-runner
To remove all shared state from your device's CPU and memory after each test, use the clearPackageData flag.

Check if DTC service is turned on in C#

When Distributed Transaction Coordinator (DTC) is not running, our MVC C# site throws strange misleading errors, confusing developers and testers. We want to do a code check that the service is running and flag the issue on something like Global.asax. Any way to do this?
The below code starts the MSDTC service on the local machine if it's currently "Stopped"
You need to reference the System.ServiceProcess assembly
using(var msDtcSvc = new System.ServiceProcess.ServiceController("MSDTC"))
{
if(msDtcSvc.Status == System.ServiceProcess.ServiceControllerStatus.Stopped)
{
msDtcSvc.Start();
}
}

SQLite callback causes recursive exceptions after a successful return

I am developing this Delhi 2009 app with SQLite database version 3.7.9, accessed by the Zeos components. Started off OK - I can create a DB if none exists, create tables and insert records - the 'normal stuff'. There is a little table that contains serial params for a connection to some old equipments and the serial comms handler needs to be informed of connection parameter changes, but the Zeos components do not support events on SQLite.
I looked at the SQLite API and there is a 'Data change notification callback', so I set about making this happen. The setup prototype is:
void *sqlite3_update_hook(
sqlite3*,
void(*)(void *,int ,char const *,char const *,sqlite3_int64),
void*
);
So, in Delphi, I imported the DLL call:
function sqlite3_update_hook(pDB:pointer;pCallback:pointer;aux:pointer): pointer; stdcall;
..
function sqlite3_update_hook; external 'sqlite3.dll' name 'sqlite3_update_hook';
..and declared an empty callback for testing:
function DBcallback(aux:pointer;CBtype:integer;CBdatabaseName:PChar;CBtableName:PChar;CBrowID:Int64):pointer; stdcall;
begin
end;
..and called the setup:
sqlite3_update_hook(SQLiteHandle,#DBcallback,dmOilmon);
SQLiteHandle is the sqlite3* pointer for the database as retrieved from the driver after connection. dmOilmon is the DataModule instance so that, when working correctly, I can call some method from the callback, (yes, I know callback is in an unknown thread - I can deal with that OK, I'll just be signaling semaphores).
Good news: when I ran the app, the DBcallback was called, aparrently successfully, upon the first insert. Bad news: some little time later, the app blew up with 'Too many exceptions', and usually a CPU window full of '??', (the occasional alternative was system death and a reboot - Vista Ultimate 64). Breaking in the callback, aux, CBtype and CBrowID were all as expected but the debugger tooltip showed the CBdatabaseName / CBtableName PChars to be pointing at a string of Chinese characters..
I tried to trace where the callback is called from - the call chain passes through in the Zeos driver code, for some reason. Breaking there and stepping through, I checked the stack pointer and it's the same before and after the callback.
So, I set up the 'empty' callback, the callback gets called at the expected point but with a coupe of dodgy-looking parameters, the callback returns to whence it came with the SP correct. I seem to have done everything right, but... :((
Has anyone seen this, (or fixed it even:)?
Can you suggest a mechanism whereby an aparrently successful callback can pesuade an app to later generate recursive exceptions?
Does anyone have any suggestions for further debugging?
Rgds,
Martin
You have the problems with correct translation of SQLite header to Delphi and with linking:
Not stdcall, but must be cdecl.
Your function DBcallback must be a procedure. Because void(*)(...) is a pointer to C function returning void.
Not PChar, but must be PAnsiChar. For non-Unicode Delphi's it may be not important, for Unicode Delphi's, it is only a correct translation.
You are using compile-time dynamic linking (external 'sqlite3.dll' ...) to sqlite3.dll. But ZeosLib uses run-time dynamic linking (LoadLibrary & GetProcAddress). That may lead to "DLL hell" issue, when your EXE loads one sqlite3.dll, and ZeosLib plans to load another sqlite3.dll.

node.js process out of memory error

FATAL ERROR: CALL_AND_RETRY_2 Allocation Failed - process out of memory
I'm seeing this error and not quite sure where it's coming from. The project I'm working on has this basic workflow:
Receive XML post from another source
Parse the XML using xml2js
Extract the required information from the newly created JSON object and create a new object.
Send that object to connected clients (using socket.io)
Node Modules in use are:
xml2js
socket.io
choreographer
mysql
When I receive an XML packet the first thing I do is write it to a log.txt file in the event that something needs to be reviewed later. I first fs.readFile to get the current contents, then write the new contents + the old. The log.txt file was probably around 2400KB around last crash, but upon restarting the server it's working fine again so I don't believe this to be the issue.
I don't see a packet in the log right before the crash happened, so I'm not sure what's causing the crash... No new clients connected, no messages were being sent... nothing was being parsed.
Edit
Seeing as node is running constantly should I be using delete <object> after every object I'm using serves its purpose, such as var now = new Date() which I use to compare to things that happen in the past. Or, result object from step 3 after I've passed it to the callback?
Edit 2
I am keeping a master object in the event that a new client connects, they need to see past messages, objects are deleted though, they don't stay for the life of the server, just until their completed on client side. Currently, I'm doing something like this
function parsingFunction(callback) {
//Construct Object
callback(theConstructedObject);
}
parsingFunction(function (data) {
masterObject[someIdentifier] = data;
});
Edit 3
As another step for troubleshooting I dumped the process.memoryUsage().heapUsed right before the parser starts at the parser.on('end', function() {..}); and parsed several xml packets. The highest heap used was around 10-12 MB throughout the test, although during normal conditions the program rests at about 4-5 MB. I don't think this is particularly a deal breaker, but may help in finding the issue.
Perhaps you are accidentally closing on objects recursively. A crazy example:
function f() {
var shouldBeDeleted = function(x) { return x }
return function g() { return shouldBeDeleted(shouldBeDeleted) }
}
To find what is happening fire up node-inspector and set a break point just before the suspected out of memory error. Then click on "Closure" (below Scope Variables near the right border). Perhaps if you click around something will click and you realize what happens.

Resources