Active Directory related AppDomainUnloadedException in MVC4 - asp.net-mvc-4

I have an ASP.NET MVC application. It's run on a domain and we determine the user by calling UserPrincipal.Current. This works beautifully, most of the time. Every once in a while (maybe 1 out of 5 times), and only right after I publish my app to IIS, it will throw an AppDomainUnloadedException.
The specific line of my code causing the exception is:
if (UserPrincipal.Current.SamAccountName != null &&
_currentUserId != UserPrincipal.Current.SamAccountName) ...
The remainder of the call stack is:
mscorlib.dll!System.StubHelpers.StubHelpers.GetCOMHRExceptionObject(int hr, System.IntPtr pCPCMD, object pThis) + 0xe bytes
System.DirectoryServices.AccountManagement.dll!System.DirectoryServices.AccountManagement.ADStoreCtx.LoadDomainInfo() + 0x358 bytes
System.DirectoryServices.AccountManagement.dll!System.DirectoryServices.AccountManagement.ADStoreCtx.DnsDomainName.get() + 0x5e bytes
System.DirectoryServices.AccountManagement.dll!System.DirectoryServices.AccountManagement.ADStoreCtx.GetAsPrincipal(object storeObject, object discriminant = {Name = "UserPrincipal" FullName = "System.DirectoryServices.AccountManagement.UserPrincipal"}) + 0x17a bytes
System.DirectoryServices.AccountManagement.dll!System.DirectoryServices.AccountManagement.ADStoreCtx.FindPrincipalByIdentRefHelper(System.Type principalType, string urnScheme, string urnValue, System.DateTime referenceDate, bool useSidHistory) + 0x576 bytes
System.DirectoryServices.AccountManagement.dll!System.DirectoryServices.AccountManagement.ADStoreCtx.FindPrincipalByIdentRef(System.Type principalType, string urnScheme, string urnValue, System.DateTime referenceDate) + 0x35 bytes
System.DirectoryServices.AccountManagement.dll!System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithTypeHelper(System.DirectoryServices.AccountManagement.PrincipalContext context, System.Type principalType, System.DirectoryServices.AccountManagement.IdentityType? identityType, string identityValue, System.DateTime refDate) + 0x9e bytes
System.DirectoryServices.AccountManagement.dll!System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithType(System.DirectoryServices.AccountManagement.PrincipalContext context, System.Type principalType, System.DirectoryServices.AccountManagement.IdentityType identityType, string identityValue) + 0x5b bytes
System.DirectoryServices.AccountManagement.dll!System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DirectoryServices.AccountManagement.IdentityType identityType, string identityValue) + 0x1e bytes
System.DirectoryServices.AccountManagement.dll!System.DirectoryServices.AccountManagement.UserPrincipal.Current.get() + 0xc1 bytes
After a great deal of digging around, and due to the random nature of the exception, I concluded the problem was probably related to this:
http://support.microsoft.com/kb/2683913
So I installed the hotfix and as expected, the problem went away. That was Tuesday. This morning, the exception started up again. I verified that the hotifx is in fact installed. I turned on module load messages and got:
'w3wp.exe': Loaded 'C:\Windows\SysWOW64\activeds.dll', Cannot find or open the PDB file.
So I verified that that .dll is in fact the one from the hotfix and it is (size and version #s match).
At the same time I get this exception, I get this event in the event log:
A process serving application pool 'WebSitePool' suffered a fatal communication error with the Windows Process Activation Service. The process id was '7404'. The data field contains the error number.
The only data in the error is: 0x8007006D which I believe simply means there was a fatal communication error which the error already said...
Humorously, when the exception dialog pops up it states, "If there is a handler for this exception, the program may be safely continued." Which is true if your app has no need for UserPrincipal.Current, but calling it again after this exception causes the exception to rethrow, so I'd question their "safely continued" assertion there.
Now, if I rerun the app, I won't get a problem. I have yet to have this happen any time, other than right after publishing. Because of our setup and relations to other projects, this app must be debugged under IIS, which means I have to publish it every time I make a code change which means I normally see this throughout the day (Tuesday afternoon and yesterday being the exceptions).
It seems curious to me that, from digging around, it appears this bug is frequently associated with ASP.NET MVC, but I don't believe I've seen it associated with WinForms or ASP.NET... I can't see how that would matter, but maybe there's a relationship there.
I suspect this is an MS bug. I can't imagine that there's any legitimate condition under which UserPrincipal.Current should cause an AppDomainUnloadedException, but I thought I'd take a shot here on Stackoverflow...

Related

FluentAssertions throws ArgumentOutOfRangeException when assertion fails (possibly NCrunch related)

I'm using FluentAssertions 5.3.0 run under NCrunch 3.14.0.1. When a test fails, I often seen this error as FluentAssertions tries to generate a report message...
System.ArgumentOutOfRangeException: startIndex cannot be larger than
length of string. Parameter name: startIndex at
System.String.Substring(Int32 startIndex, Int32 length) at
FluentAssertions.CallerIdentifier.ExtractVariableNameFrom(StackFrame
frame) at
FluentAssertions.CallerIdentifier.DetermineCallerIdentity() at
FluentAssertions.Execution.AssertionScope.GetIdentifier() at
FluentAssertions.Execution.AssertionScope.FailWith(String message,
Object[] args) at FluentAssertions.Numeric.NumericAssertions`1.Be(T
expected, String because, Object[] becauseArgs) at
TableTests.ConsolidatedMovementsTester.AlternativingMovementStatesAreRecognised()
in ...test.cs
The error is sporadic - often it will disappear if the test is rerun (in which case, a proper error report is shown). I've seen this in the last couple of versions of both FluentAssertions and NCrunch and it appears on multiple machines (all running some flavour of Visual Studio 2017 Professional).
Here's an example of the latest call to bite me...
results.Count(c => c.IsStationary).Should().Be(5);
where results is an ImmutableArray of POCOs
In this case, right-clicking on the failing test and selecting "rerun in new test runner" in the ncrunch window, caused the test to re-run and FA to emit the correct report.
Can anyone suggest a workaround for this?

Importing data from multi-value D3 database into SQL issues

Trying to use the mv.NET by bluefinity tools. Made some integration packages with it for importing data from a d3 multi-value database into MS SQL 2012 but seem to be having some trouble with the mapping.
For the VOYAGES table have some commentX fields in the D3 application that are acting quite unwieldy and the INSERT fails after a certain number of rows with the following message
>Error: 0xC0047062 at INSERT, mvNET Source[354]: System.Exception: Error #8: dataReader[0] = LTPAC002 ci.BufferColumnIndex = 52, ci.ColumnName = COMMGROUP(Error #8: dataReader[0] = LTPAC002 ci.BufferColumnIndex = 52, ci.ColumnName = COMMGROUP(The value is too large to fit in the column data area of the buffer.))
at mvNETDataSource.mvNETSource.PrimeOutput(Int32 outputs, Int32[] outputIDs, PipelineBuffer[] buffers)
at Microsoft.SqlServer.Dts.Pipeline.ManagedComponentHost.HostPrimeOutput(IDTSManagedComponentWrapper100 wrapper, Int32 outputs, Int32[] outputIDs, IDTSBuffer100[] buffers, IntPtr ppBufferWirePacket)
Error: 0xC0047038 at INSERT, SSIS.Pipeline: SSIS Error Code DTS_E_PRIMEOUTPUTFAILED.The PrimeOutput method on mvNET Source returned error code 0x80131500.The component returned a failure code when the pipeline engine called PrimeOutput().The meaning of the failure code is defined by the component, but the error is fatal and the pipeline stopped executing.There may be error messages posted before this with more information about the failure.
The value is too large to fit in the column data area of the buffer. -> tried changing the input / outputs types but can't seem to get it right.
In the SQL table the columns are of type ntext.
In the .dtsx job the data type for the columns are of type Unicode String [DT_WSTR] with length 4000 , I guess these are auto-detected.
The import worked for other D3 files like this not sure why it fails for these comment fields.
Running the query on the mv.NET Data Manager ( on the d3 server) times out after 240 seconds so maybe this is the underlying issue?
Any ideas how to proceed? Thank you ~
Most like reason is column COMMGROUP does not have correct data type or some record in source do not fit in output type
To find error record (causing) you have to use on redirect row (property of component failing component ) and get the result set in some txt.csv /or tsv file .
then check data
The exception is being thrown from mv.NET so I suggest you call (or ask your reseller) to call Bluefinity support and ask them about this. You're paying for support, might as well use it. Those programs shouldn't be allowed to throw exceptions like that.
D3 doesn't export Unicode, that might be one issue. But if the Data Manager times-out then I suspect something is wrong in the connectivity into D3. Open a Connection Monitor from the Session Monitor and watch the connection when you make the request. I'm guessing it's either hanging or more probably it's falling into BASIC Debug.
Make sure all D3-side programs related to this are either all Flash-compiled, or all Not Flashed. Your app code will fall into Debug if it's not Flashed but MVNET.BP is.
If it's your program that's in Debug, fix it. If you're not sure which program it is, LIST-RUNTIME-ERRORS in DM.
If it's a MVNET.BP program, again work with Bluefinity. If you are using MVSP for connectivity then the Connection Monitor may be useless, you'll need to change that to an IP (Telnet) connection to see the raw data exchange.

Setting a timeout on webservice consumer built with org.apache.axis.client.Call and running on Domino

I'm maintaining an antedeluvian Notes application which connects to a SAP back-end via a manually done 'Webservice'
The server is running Domino Release 7.0.4FP2 HF97.
The Webservice is not the more recently Webservice Consumer, but a large Java agent which is using Apache soap.jar (org.apache.soap). Below an example of the calling code.
private Call setupSOAPCall() {
Call call = new Call();
SOAPHTTPConnection conn = new SOAPHTTPConnection();
call.setSOAPTransport(conn);
call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);
There has been a change in the SAP system which is now taking 8 minutes to complete (verified by SAP Team).
I'm getting an error message as follows:
[SOAPException: faultCode=SOAP-ENV:Client; msg=For input string: "906 "; targetException=java.lang.NumberFormatException: For input string: "906 "]
I found a blog article describing the error message quite closely:
https://thejavablog.wordpress.com/category/jmeter/
and I've come to the hypothesis that it is a timeout message that is returning to my Call object and that this timeout message is being incorrectly parsed, hence the NumberFormat Exception.
Looking at my logs I can see that there is a time difference of 62 seconds between my call and the response.
I recommended that the server setting in the server document, tab Internet Protocols/HTTP/Timeouts/Request timeouts be changed from 60 seconds to 600 seconds, and the http task restarted with
tell http restart
I've re-run the tests and I am getting the same error, and the time difference is still slightly more than 60 seconds, which is not what I was expecting.
I read Michael Rulnau's blog entry
http://www.mruhnau.net/2014/06/how-to-overcome-domino-webservice.html
which points to this APR
http://www-01.ibm.com/support/docview.wss?uid=swg1LO48272
but I'm not convinced that this would apply in this case, since there is no way that IBM would know that my Java agent is in fact making a Soap call.
My current hypothesis is that I have to use either the setTimeout() method on
org.apache.axis.client.Call
https://axis.apache.org/axis/java/apiDocs/org/apache/axis/client/Call.html
or on the org.apache.soap.transport.http.SOAPHTTPConnection
https://docs.oracle.com/cd/B13789_01/appdev.101/b12024/org/apache/soap/transport/http/SOAPHTTPConnection.html
and that the timeout value is an apache default, not something that is controlled by the Domino server.
I'd be grateful for any help.
I understand your approach, and I hope this is the correct one to solve your problem.
Add a debug (console write would be fine) that display the default Timeout then try to increase it to 10 min.
SOAPHTTPConnection conn = new SOAPHTTPConnection();
System.out.println("time out is :" + conn.getTimeout());
conn.setTimeout(600000);//10 min in ms
System.out.println("after setting it, time out is :" + conn.getTimeout());
call.setSOAPTransport(conn);
Now keep in mind that Dommino has also a Max LotusScript/Java execution time, check this value and (at least for a try) change it: http://www.ibm.com/support/knowledgecenter/SSKTMJ_9.0.1/admin/othr_servertasksagentmanagertab_r.html (it's version 9 help but this part should be identical)
I've since discovered that it wasn't my code generating the error; the default timeout for the apache axis SOAPHTTPConnetion is 0, i.e. no timeout.

Why does my code run 2 different ways with the exact same code?

I have an application that I have started developing that monitors websocket messages from all clients connected to the websocket server by relaying all messages received from the server to this application.
Problem
When I run my program (In visual studio I hit Start), it builds and starts up perfectly, and does most of the functionality the same everytime. However, I have a common occurance of a portion of code that will not run the same. Below is the small snippet of that code.
msg = "set name monitor"
SendMessage2(socket, msg, msg.Length)
msg = "set monitor 1"
SendMessage2(socket, msg, msg.Length)
Console.WriteLine("We are after our second SendMessage2 function")
I know that the two calls to SendMessage2 are always executed because visual studio's debug console will output the following
We are at the end of the SendMessage2 Sub
We are at the end of the SendMessage2 Sub
We are after our second SendMessage2 function
I also know when it executes correctly because my websocket server will either output one of the two blocks
Output when app runs correctly
Client 4 connected
New thread created
Connection received. Parsing headers.
Message from socket #4: "set name monitor"
Message from socket #4: "set monitor 1"
Output when app runs incorrectly
Client 4 connected
New thread created
Connection received. Parsing headers.
Message from socket #4: "set name monitor"
Notice how the second output is missing the second message from the monitor application.
What have I tried
Using a string variable to call the functions
Calling the functions using static string arguments (not using the variable msg)
SyncLocking the functions separately
SyncLocking inside the SendMessage2 function
Reordering the functions (swapping the strings to change behavior)
TL;DR
Why is it that even when I do not change my code, my program will execute two separate ways? Am I doing something incorrectly when calling my SendMessage2 Sub?
I am all out of ideas. I am willing to try any recommendation to fix this problem.
All code can be found on GitHub here
So I figured it out.
It is actually not the VB application that is messing up. Nor was my server. While debugging I was looking at the number of bytes received by my server and I noticed the following:
Client 4 connected
New thread created
Connection received. Parsing headers.
bytes read: 25
Message from socket #4: "set name monitor"
bytes read: 22
Message from socket #4: "set monitor 1"
Ok great we have 25 bytes from set name monitor and 22 bytes from set monitor 1
Client 4 connected
New thread created
Connection received. Parsing headers.
bytes read: 47
Message from socket #4: "set name monitor"
And boom. Both programs were doing their jobs, sending the correct number of bytes every time and reading the correct number. However, the VB application is sending them so quickly back to back that my server was reading all 47 bytes at a time instead of the separate 25 and 22 bytes.
Solution
I solved this problem by implementing a secondary buffer in my server to store off all bytes after the first message should multiple messages by group like this. Now I check if my secondaryBuffer is empty before reading in new bytes.
Here is a portion of the code used to solve the problem
/*Byte Check*/
for (j=0; j < bytes; j++) {
if (j == 0)
continue;
if (readBuffer[j] == '\x81' && readBuffer[j-1] == '\x00' && readBuffer[j-2] == '\x00') {
secondaryBytes = bytes - j;
printf("Potential second message attached to this message\nCopying it to the secondary buffer.\n");
memcpy(secondaryBuffer, readBuffer + j, secondaryBytes);
break;
}//END IF
}//END FOR LOOP
/**/

Unhandled Exception using DotNetZip

I've been using DotNetZip for a month or so now and i like how it has worked but today my program started having a new issue that I'm clueless on.
During the zipping process it throws this error up and windows displays their "program name has stopped working" box.
Unhandled Exception: System.IO.FileNotFoundException: s:\(file path)\filename.pdf
at Ionic.Zip.SharedUtilities.GetFileLength(string fileName)
at ionic.Zip.ZipEntry.MaybeUnsetCompressionMethodForWriting(int32 cycle)
at Ionic.zip.Zipentry.WriteHeader(Stream s, Int32 cycle)
at Ionic.zip.ZipEntry.Write(Stream s)
at Ionic.zip.zipfile.save()
at ZipAJob_Instant.ConsoleMain.Main() in C:\users\(my name)\Documents\visual studio 2012\projects\zipAjob_Instant\zipAJob_Win32.vb:line 71
Line 71 refers to where i call zip.save()
From your comments, I take that what happened is exactly what happened to me a while ago.
I was getting a list of files to zip and stored into memory. The I would go zipping them one by one until this exception was thrown. The cause was someone removed the file after I got the list, but before I got the opportunity to zip it. This occured on a shared folder, btw.