Debug "An item with the same key has already been added" exception - windbg

I took a crash dump of my application when I got the "An item with the same key has already been added" exception. I need help finding which object caused this exception. I could print the exception but couldn't figure out how to find the exact key that caused the exception.

This is likely the state you have:
[...]
(3250.7ec): CLR exception - code e0434352 (!!! second chance !!!)
[...]
0:000> .loadby sos clr
0:000> !pe
Exception object: 030c31e8
Exception type: System.ArgumentException
Message: An item with the same key has already been added.
InnerException: <none>
StackTrace (generated):
SP IP Function
010FEE1C 6045F705 mscorlib_ni!System.ThrowHelper.ThrowArgumentException(System.ExceptionResource)+0x35
010FEE2C 609410C7 mscorlib_ni!System.Collections.Generic.Dictionary`2[[System.__Canon, mscorlib],[System.__Canon, mscorlib]].Insert(System.__Canon, System.__Canon, Boolean)+0xc6af67
010FEE60 5FD4B310 mscorlib_ni!System.Collections.Generic.Dictionary`2[[System.__Canon, mscorlib],[System.__Canon, mscorlib]].Add(System.__Canon, System.__Canon)+0x10
010FEE68 017004F5 KeyAlreadyAdded!KeyAlreadyAdded.Program.Main()+0x45
[...]
In the native call stack, you can see the call to Dictionary.Add() again, but with the additional information for the frame number:
0:000> k
# ChildEBP RetAddr
00 010fecb0 618fac03 KERNELBASE!RaiseException+0x62
01 010fed4c 618fae08 clr!RaiseTheExceptionInternalOnly+0x27c
02 010fee14 6045f705 clr!IL_Throw+0x141
03 010fee24 609410c7 mscorlib_ni!System.ThrowHelper.ThrowArgumentException(System.ExceptionResource)$##6000335+0x35
04 010fee50 5fd4b310 mscorlib_ni![COLD] System.Collections.Generic.Dictionary`2[System.__Canon,System.__Canon].Insert(System.__Canon, System.__Canon, Boolean)$##6003922+0x87
05 010fee68 6181ebe6 mscorlib_ni!System.Collections.Generic.Dictionary`2[System.__Canon,System.__Canon].Add(System.__Canon, System.__Canon)$##6003915+0x10
[...]
At the Insert() method, you can use the ebx register to get the key:
0:000> .frame /r 4
04 010fee50 5fd4b310 mscorlib_ni![COLD] System.Collections.Generic.Dictionary`2[System.__Canon,System.__Canon].Insert(System.__Canon, System.__Canon, Boolean)$##6003922+0x87
eax=010fec58 ebx=030c2364 ecx=00000005 edx=00000000 esi=030c23b0 edi=030c2364
[...]
0:000> !do 030c2364
Name: System.String
MethodTable: 5fdefd60
EEClass: 5f9c4e90
Size: 22(0x16) bytes
File: C:\Windows\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll
String: this
[...]
So in this case, the duplicate key being added is the string "this". Here's the code:
using System.Collections.Generic;
namespace KeyAlreadyAdded
{
class Program
{
static Dictionary<string, string> dict = new Dictionary<string, string> {{"this", "was already inside"}};
static void Main()
{
dict.Add("that", "goes in easily");
dict.Add("this", "however, causes a duplicate key exception");
}
}
}

Related

What would cause a try/catch block to fail exception handling despite execution landing in catch block?

The execution from below code
line 108 try
line 109 {
line 110 columnValCSV = columns_List(fileNumber)(columnNumber)
line 111 }
line 112 catch
line 113 {
line 114 case e: Exception => println(columnValCSV +"OtherLogText")
line 115 }
lands in the catch block as shown in the stack trace.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
10 at Main$.$anonfun$parseSecondDataSource$2(Main.scala:114) at
Main$.$anonfun$parseSecondDataSource$2$adapted(Main.scala:85) at
scala.collection.Iterator.foreach(Iterator.scala:929) at
scala.collection.Iterator.foreach$(Iterator.scala:929) at
scala.collection.AbstractIterator.foreach(Iterator.scala:1417) at
Main$.$anonfun$parseSecondDataSource$1(Main.scala:85) at
Main$.$anonfun$parseSecondDataSource$1$adapted(Main.scala:68) at
scala.collection.mutable.ResizableArray.foreach(ResizableArray.scala:59)
at
scala.collection.mutable.ResizableArray.foreach$(ResizableArray.scala:52)
at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
at Main$.parseSecondDataSource(Main.scala:68) at
Main$.main(Main.scala:147) at Main.main(Main.scala)
However, instead of avoiding throwing an exception as my code is supposed to do, it crashes.
An exception handler can also throw.
scala> try throw null catch { case _: NullPointerException => ??? }
scala.NotImplementedError: an implementation is missing
at scala.Predef$.$qmark$qmark$qmark(Predef.scala:347)
at .liftedTree1$1(<console>:1)
... 28 elided
The actual print statement in the catch block references the same variable I put in the try block. That was the problem

Proper handling of std.getopt.GetOptException

What is the proper handling of the std.getopt.GetOptException Exception that is thrown when a required command line argument is missing.
Declaring an argument being required throws the following error which is way too verbose:
std.getopt.GetOptException#/Library/D/dmd/src/phobos/std/getopt.d(755): Required option file|f was not supplied
----------------
/Library/D/dmd/src/phobos/std/format.d-mixin-1127:1138 #safe std.getopt.GetoptResult std.getopt.getopt!(std.getopt.config, immutable(char)[], immutable(char)[], immutable(char)[]*, std.getopt.config, immutable(char)[], immutable(char)[], immutable(char)[]*, immutable(char)[], immutable(char)[], bool*, immutable(char)[], immutable(char)[], bool*).getopt(ref immutable(char)[][], std.getopt.config, immutable(char)[], immutable(char)[], immutable(char)[]*, std.getopt.config, immutable(char)[], immutable(char)[], immutable(char)[]*, immutable(char)[], immutable(char)[], bool*, immutable(char)[], immutable(char)[], bool*) [0xbb5a9d1]
source/app.d:11 _Dmain [0xbb58996]
std.getopt.GetOptException#/Library/D/dmd/src/phobos/std/getopt.d(755): Required option key|k was not supplied
Use the following code to reproduce it:
import std.stdio;
import std.getopt;
int main(string[] args)
{
string key;
string inputFile;
bool encrypt;
bool decrypt;
auto result = getopt(
args,
std.getopt.config.required,
"key|k", "The key to use", &key,
std.getopt.config.required,
"file|f", "The file to encrypt/decrypt", &inputFile,
"encrypt|e", "Encrypt the file", &encrypt,
"decrypt|d", "Decrypt the file", &decrypt
);
if (result.helpWanted) {
defaultGetoptPrinter("Some information about the program.", result.options);
}
return 0;
}
A reasonable way to do this is to wrap the getopt call in a try-catch block, catch any error, and write only the error message part before exiting. This will avoid the writing the stack trace, which is not helpful to most users. Modifying the above example:
import std.stdio;
import std.getopt;
int main(string[] args)
{
string key;
string inputFile;
bool encrypt;
bool decrypt;
try {
auto result = getopt(
args,
std.getopt.config.required,
"key|k", "The key to use", &key,
std.getopt.config.required,
"file|f", "The file to encrypt/decrypt", &inputFile,
"encrypt|e", "Encrypt the file", &encrypt,
"decrypt|d", "Decrypt the file", &decrypt
);
if (result.helpWanted) {
defaultGetoptPrinter("Some information about the program.", result.options);
}
}
catch (Exception e) {
stderr.writefln("Error processing command line arguments: %s", e.msg);
return 1;
}
return 0;
}
The error message when run:
Error processing command line arguments: Required option file|f was not supplied
There's a thread on the D language 'Learn' forum related to this that might be useful: What's the proper way to use std.getopt?. I've written some open source command line tools that are a bit more extensive examples, eg. tsv-sample.d.

Custom MessageBodyReader not found in JerseyTest

I am having a bizarre problem with my JerseyTest class.
When executing my test code and putting a break point on line 203 of org.glassfish.jersey.message.internal.ReaderInterceptorExecutor, I see that my reader is not in reader.workers. However, as you can see below, I register this MessageBodyReader in the ResourceConfig.
All relevant code is provided below.
My custom MessageBodyReader/Writer
#Provider
#Produces({V1_JSON})
#Consumes({V1_JSON})
public class JsonMessageBodyHandlerV1
implements
MessageBodyWriter<Object>,
MessageBodyReader<Object> {
...
}
And yes, isReadable returns true.
When debugging, I see that the code hits writeTo but not readFrom.
Test code that fails
public class TestLocationResource extends JerseyTest {
public static class LocationResourceHK2Binder extends AbstractBinder {
#Override
protected void configure() {
// Singleton bindings.
bindAsContract(LocationDao.class).in(Singleton.class);
// Singleton instance bindings.
bind(new FakeLocationDao()).to(LocationDao.class);
}
}
#Test
public void basicTest() {
LocationListV1 actualResponse = /**/
/**/target(LocationResourceV1.PathFields.PATH_ROOT)
/* */.path(LocationResourceV1.PathFields.SUBPATH_LIST)
/* */.request(V1_JSON)
/* */.header(HEADER_API_KEY, "abcdefg")
/* */.get(LocationListV1.class);
assertEquals(10, actualResponse.getLocations().size());
}
#Override
protected Application configure() {
enable(TestProperties.LOG_TRAFFIC);
enable(TestProperties.DUMP_ENTITY);
ResourceConfig rc = new ResourceConfig();
rc.registerClasses(LocationResourceV1.class, JsonMessageBodyHandlerV1.class);
rc.register(new LocationResourceHK2Binder());
return rc;
}
}
(Pulling from this example.)
The resource it's testing...
public class LocationResourceV1 implements ILocationResourceV1 {
...
#Inject
private LocationDao daoLoc;
private final LocationTranslator translator = new LocationTranslator();
#Override
public LocationListV1 listV1(String apiKey) {
return translator.translate(daoLoc.query(LocationFilters.SELECT_ALL));
}
...
#VisibleForTesting
public void setLocationDao(LocationDao dao) {
this.daoLoc = dao;
}
}
(Note that the web service annotations such as #GET are in the interface.)
Generates this fail trace
org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException:
MessageBodyReader not found for media
type=application/vnd.com.company-v1+json, type=class
com.company.rest.v1.resources.location.json.LocationListV1,
genericType=class
com.company.rest.v1.resources.location.json.LocationListV1.
at
org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:207)
at
org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:139)
at
org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:1109)
at
org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:851)
at
org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:785)
at
org.glassfish.jersey.client.InboundJaxrsResponse.readEntity(InboundJaxrsResponse.java:96)
at
org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:761)
at
org.glassfish.jersey.client.JerseyInvocation.access$500(JerseyInvocation.java:90)
at
org.glassfish.jersey.client.JerseyInvocation$2.call(JerseyInvocation.java:671)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315) at
org.glassfish.jersey.internal.Errors.process(Errors.java:297) at
org.glassfish.jersey.internal.Errors.process(Errors.java:228) at
org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:422)
at
org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:667)
at
org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:396)
at
org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:296)
at
com.company.rest.resources.location.TestLocationResource.basicTest(TestLocationResource.java:47)
[...]
... with this console output
[...]
INFO: [HttpServer] Started.
Oct 29, 2013 4:26:16 PM org.glassfish.jersey.filter.LoggingFilter log
INFO: 1 * LoggingFilter - Request received on thread main
1 > GET http://localhost:9998/location/list
1 > Accept: application/vnd.com.company-v1+json
1 > X-ApiKey: abcdefg
Oct 29, 2013 3:30:21 PM org.glassfish.jersey.internal.Errors logErrors
WARNING: The following warnings have been detected: WARNING: HK2 service reification failed for [com.company.persistence.dao.intf.LocationDao] with an exception:
MultiException stack 1 of 2
java.lang.NoSuchMethodException: Could not find a suitable constructor in com.company.persistence.dao.intf.LocationDao class.
at org.glassfish.jersey.internal.inject.JerseyClassAnalyzer.getConstructor(JerseyClassAnalyzer.java:189)
at org.jvnet.hk2.internal.Utilities.getConstructor(Utilities.java:159)
at org.jvnet.hk2.internal.ClazzCreator.initialize(ClazzCreator.java:125)
at org.jvnet.hk2.internal.ClazzCreator.initialize(ClazzCreator.java:176)
at org.jvnet.hk2.internal.SystemDescriptor.internalReify(SystemDescriptor.java:649)
at org.jvnet.hk2.internal.SystemDescriptor.reify(SystemDescriptor.java:604)
at org.jvnet.hk2.internal.ServiceLocatorImpl.reifyDescriptor(ServiceLocatorImpl.java:396)
[...]
MultiException stack 2 of 2
java.lang.IllegalArgumentException: Errors were discovered while reifying SystemDescriptor(
implementation=com.company.persistence.dao.intf.LocationDao
contracts={com.company.persistence.dao.intf.LocationDao}
scope=org.glassfish.jersey.process.internal.RequestScoped
qualifiers={}
descriptorType=CLASS
descriptorVisibility=NORMAL
metadata=
rank=0
loader=org.glassfish.hk2.utilities.binding.AbstractBinder$2#568bf3ec
proxiable=null
proxyForSameScope=null
analysisName=null
id=143
locatorId=0
identityHashCode=2117810007
reified=false)
at org.jvnet.hk2.internal.SystemDescriptor.reify(SystemDescriptor.java:615)
at org.jvnet.hk2.internal.ServiceLocatorImpl.reifyDescriptor(ServiceLocatorImpl.java:396)
at org.jvnet.hk2.internal.ServiceLocatorImpl.narrow(ServiceLocatorImpl.java:1916)
at org.jvnet.hk2.internal.ServiceLocatorImpl.access$700(ServiceLocatorImpl.java:113)
at org.jvnet.hk2.internal.ServiceLocatorImpl$6.compute(ServiceLocatorImpl.java:993)
at org.jvnet.hk2.internal.ServiceLocatorImpl$6.compute(ServiceLocatorImpl.java:988)
[...]
[...]
(Above is repeated 4 times)
[...]
[...]
Followed by this, implying that there was a successful response
Oct 29, 2013 3:30:22 PM org.glassfish.jersey.filter.LoggingFilter log
INFO: 2 * LoggingFilter - Response received on thread main
2 < 200
2 < Date: Tue, 29 Oct 2013 22:30:21 GMT
2 < Content-Length: 16
2 < Content-Type: application/vnd.com.company-v1+json
{"locations":[]}
Oct 29, 2013 3:30:22 PM org.glassfish.jersey.test.grizzly.GrizzlyTestContainerFactory$GrizzlyTestContainer stop
INFO: Stopping GrizzlyTestContainer...
Oct 29, 2013 3:30:22 PM org.glassfish.grizzly.http.server.NetworkListener stop
INFO: Stopped listener bound to [localhost:9998]
Anybody have any idea what I am doing wrong?
The first stack-trace comes from your client because you didn't register your message-body provider there (and hence it cannot be found). JerseyTest#configure method is supposed to be used to configure only the server-side. There is another method called JerseyTest#configureClient intended to be used on the client-side. You need to override both methods if you want to use a custom provider.
The second stack-trace comes from your LocationResourceHK2Binder. By
bindAsContract(LocationDao.class).in(Singleton.class);
you're telling HK2 that LocationDao class should be instantiated as a singleton and HK2 would then inject it to LocationDao types. You may want to change your binder to use something like:
bind(new FakeLocationDao()).to(LocationDao.class);
For more information on this topic, refer to Custom Injection and Lifecycle Management.

Magento API error --- SoapHeaderException: Procedure 'login' not present

I am lost. I do not even know where to begin. This is the error I am getting:
Procedure 'login' not present
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.Services.Protocols.SoapHeaderException: Procedure 'login' not present
Source Error:
Line 375: service.Url = account.APIURL;
Line 376:
Line 377: string sessionId = service.login(account.APIUser, account.APIPassword);
Line 378:
Line 379: var orders = service.salesOrderList(sessionId, InitialiseSOAPOrderCriteria(account.TriggerOrderStatus));
Source File: c:\inetpub\wwwroot\UAT.SFSystem\Settings\ChannelHeader.ascx.cs Line: 377
Stack Trace:
[SoapHeaderException: Procedure 'login' not present]
System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall) +1772421
System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) +345
Adapters.MagentoSOAP.MagentoSOAP.MagentoService.login(String username, String apiKey) in C:\Work\WebCatch\SF\StoreFeeder\Middlewares\SFMWMagento\Adapters.MagentoSOAP\Web References\MagentoSOAP\Reference.cs:663
Settings_ChannelHeader.magentoTestConnection(String channelGuid) in c:\inetpub\wwwroot\UAT.SFSystem\Settings\ChannelHeader.ascx.cs:377
Settings_ChannelHeader.btnTestConnection_Click(Object sender, EventArgs e) in c:\inetpub\wwwroot\UAT.SFSystem\Settings\ChannelHeader.ascx.cs:154
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +154
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3707
I was getting the same error while using the v2 magento api, but problem resolved when I switched back to v1 soap api of magento

Exception occured while trying to use MsmqSubscription storage

I am newbie in NService bus and I am trying to create a bus using MSMQSubscribtion storage , but I am getting following error.
Exception when starting endpoint,
error has been logged. Reason: Error
creating object with name
'NServiceBus.Unicast.Subscriptions.Msmq.MsmqSubscriptionStorage'
: Error setting property values:
PropertyAccessExceptionsException (1
errors); nested
PropertyAccessExceptions are:
[Spring.Core.TypeMismatchException:
Cannot convert property value of type
[System.String] to required type
[System.String] for property 'Queue'.,
Inner Exception:
System.ArgumentException: There is a
problem with the subscription storage
queue . See enclosed exception for
details. --->
System.Messaging.MessageQueueException:
Format name is invalid.
at System.Messaging.MessageQueue.MQCacheableInfo.get_Transactional()
at System.Messaging.MessageQueue.get_Transactional()
at NServiceBus.Unicast.Subscriptions.Msmq.MsmqSubscriptionStorage.set_Queue(String
value) in
d:\BuildAgent-02\work\672d81652eaca4e1\src\impl\unicast\NServiceBus.Unicast.Subscriptions.Msmq\MsmqSubscriptionStorage.cs:line
184
--- End of inner exception stack trace ---
at NServiceBus.Unicast.Subscriptions.Msmq.MsmqSubscriptionStorage.set_Queue(String
value) in
d:\BuildAgent-02\work\672d81652eaca4e1\src\impl\unicast\NServiceBus.Unicast.Subscriptions.Msmq\MsmqSubscriptionStorage.cs:line
188
at (Object , Object , Object[] )
at Spring.Reflection.Dynamic.SafeProperty.SetValue(Object
target, Object value) in
l:\projects\spring-net\trunk\src\Spring\Spring.Core\Reflection\Dynamic\DynamicProperty.cs:line
204
at Spring.Expressions.PropertyOrFieldNode.PropertyValueAccessor.Set(Object
context, Object value) in
l:\projects\spring-net\trunk\src\Spring\Spring.Core\Expressions\PropertyOrFieldNode.cs:line
585
at Spring.Expressions.PropertyOrFieldNode.SetPropertyOrFieldValueInternal(Object
context, Object newValue) in
l:\projects\spring-net\trunk\src\Spring\Spring.Core\Expressions\PropertyOrFieldNode.cs:line
406
at Spring.Expressions.PropertyOrFieldNode.SetPropertyOrFieldValue(Object
context, EvaluationContext
evalContext, Object newValue) in
l:\projects\spring-net\trunk\src\Spring\Spring.Core\Expressions\PropertyOrFieldNode.cs:line
348]
This is my Config section .
<configuration>
<configSections>
<section name="MsmqTransportConfig" type="NServiceBus.Config.MsmqTransportConfig,NServiceBus.Core"/>
<section name="UnicastBusConfig" type="NServiceBus.Config.UnicastBusConfig,NServiceBus.Core"/>
<section name="MsmqSubscriptionStorageConfig"
type="NServiceBus.Config.MsmqSubscriptionStorageConfig,NServiceBus.Core" />
</configSections>
<MsmqTransportConfig InputQueue="MyResponseQueue" ErrorQueue="error" NumberOfWorkerThreads="1" MaxRetries="5"/>
<UnicastBusConfig>
<MessageEndpointMappings>
<add Messages="MyMessages.Message1" Endpoint="PubQueue"/>
</MessageEndpointMappings>
</UnicastBusConfig>
</configuration>
This is how I tried to create the bus
NServiceBus.Configure.With()
.DefaultBuilder()
.Log4Net()
.MsmqSubscriptionStorage()
.XmlSerializer()
.MsmqTransport()
.IsTransactional(true)
.UnicastBus()
.CreateBus();
Can any one explain what went wrong for me?
Any help would be much appreciated.
Thanks
Alex.
Looks like you are missing the actual MsmqSubscriptionStorageConfig section. This is required and will point to your subscription queue.
<MsmqSubscriptionStorageConfig Queue="queueName" />
NServiceBus will automatically use a queue called "NServiceBus_Subscriptions", if not defined in configuration file. Be sure to have installed MSMQ.