Item has already been added. Key in dictionary: 'path' Key being added: 'path'

Locked Item has already been added. Key in dictionary: 'path' Key being added: 'path'

  • Thursday, February 02, 2006 10:59 PM
     
     

    If I run the application by clicking on the exe then no errors, but if I run it within VS2005. it throws me this exception which I have no idea why its doing. Interestingly this only happens on my Windows 2000 professional machine, same code if I run on Windows XP Professional, it works like a charm.

    Exception:
    Item has already been added. Key in dictionary: 'path'  Key being added: 'path'

    Please update with a work around.

    Syed Hussain

All Replies

  • Friday, February 03, 2006 12:42 AM
     
     
    It looks like you're inserting duplicate keys into a dictionary object. Dictionary objects in .Net can only have unique keys. Are you using a dictionary object in your code somewhere?
  • Friday, February 03, 2006 5:52 PM
     
     

    Thanks for the  info, I know the basics of Hashtable, what I am asking why I am getting this exception if I run from the VS2005 only in Windows 2000 Professional, same code if I run inside VS2005 on Windows XP Professional no exceptions at all. More interestingly if I just run the executable by double clicking on it, so regardless of operating system it works fine. I need to debug under Windows 2000 and this is making me crazy, VS Team HELPPPPPP ME.

  • Saturday, February 04, 2006 12:54 AM
     
     Answered

    S. Hussain,

    It would help out a lot if you can provide an example of the code that is failing.  If you can reduce it to a few lines of code in a small program that will work on XP and not on 2000 it will really expedite the process.  

    For example, one common W2K compatibility bug is to assume certain OS dependencies that are available in XP will be provided to you on W2K.  Invariably those OS features weren't invented in the W2K time frame so when your code goes to call them it throws an exception on W2K but not XP.  I know this particular error message does tell you that but if the scars of years of software testing have taught me anything, error messages can't always be trusted to tell you what's right. 

    For example, depending on how your code is laid out, if you were in a hurry writing the code to begin with (not that you would ever take shortcuts) but say you had to take someone elses code and they had a try/catch block that catches all exceptions and ignores them, there could be a logic loop in the code that is getting repeated even though it shouldn't be, causing something to add to the dictionary a second time.  I don't know if that's what's happening here, but if you can reduce things into a small repro scenario and post that information here, it would help us be able to identify what is going on.

    Hope that helps.  Thanks for choosing Microsoft!

    Eric Jarvi
    http://blogs.msdn.com/ejarvi 

  • Monday, February 06, 2006 7:27 PM
     
     

    Okay I solved my own problem finally. Actually when we originally started the .NET Developement four years ago, as a part of the TAP Program Microsoft delivered exclusive Hot Fixes for us, which includes the fix for serialization. I got my new machine last week with pre installed VS2005, everything looks and runs great, except of the problem I complained about. So today I uninstalled everthing and reinstall everything with the addition of the Hot Fixes. Magically everything starts working as it was, and I think my XP machine already got those Hot Fixes so thats why I am not getting any problem with my XP machine. One problem is, if you install Framework 1.1 Service Pack 1 by Auto Update or Windows Update before this Hot Fix then you cannot install Hot Fix at all and vice versa if you install Hot Fix then you cannot install the Framework 1.1 Service Pack. Thats why I unintalled everything. But the interesting thing is still there, it gave me exception in VS2005 Debugger only if I just run the application either by the command line or just double clicking on it, no exceptions raised.

    Thanks for the reply anyways. If you need more info about this issue you can send me email on syed.hussain@hotmail.com

    Syed Hussain

  • Wednesday, May 17, 2006 5:16 PM
     
     
    Hello,

    I get the same problem when trying to serialize an object to xml using .NET 2.0 on Windows 2000 Professional.
    The same code works fine on XP.
    You mentioned you installed hotfixes, could you please tell me what are the hotfixes that solved your problem and in what order I need to install.

    Thanks for your help

    Thierry

    PS : Just for information, the stack trace looks like :
    Item has already been added. Key in dictionary: 'path'  Key being added: 'path' [System.ArgumentException: Item has already been added. Key in dictionary: 'path'  Key being added: 'path'
       at System.Collections.Hashtable.Insert(Object key, Object nvalue, Boolean add)
       at System.Collections.Hashtable.Add(Object key, Object value)
       at System.Collections.Specialized.StringDictionary.Add(String key, String value)
       at System.CodeDom.Compiler.Executor.ExecWaitWithCaptureUnimpersonated(SafeUserTokenHandle userToken, String cmd, String currentDir, TempFileCollection tempFiles, String& outputName, String& errorName, String trueCmdLine)
       at System.CodeDom.Compiler.Executor.ExecWaitWithCapture(SafeUserTokenHandle userToken, String cmd, String currentDir, TempFileCollection tempFiles, String& outputName, String& errorName, String trueCmdLine)
       at Microsoft.CSharp.CSharpCodeGenerator.Compile(CompilerParameters options, String compilerDirectory, String compilerExe, String arguments, String& outputFile, Int32& nativeReturnValue, String trueArgs)
       at Microsoft.CSharp.CSharpCodeGenerator.FromFileBatch(CompilerParameters options, String[] fileNames)
       at Microsoft.CSharp.CSharpCodeGenerator.FromSourceBatch(CompilerParameters options, String[] sources)
       at Microsoft.CSharp.CSharpCodeGenerator.System.CodeDom.Compiler.ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters options, String[] sources)
       at System.CodeDom.Compiler.CodeDomProvider.CompileAssemblyFromSource(CompilerParameters options, String[] sources)
       at System.Xml.Serialization.Compiler.Compile(Assembly parent, String ns, CompilerParameters parameters, Evidence evidence)
       at System.Xml.Serialization.TempAssembly.GenerateAssembly(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace, Evidence evidence, CompilerParameters parameters, Assembly assembly, Hashtable assemblies)
       at System.Xml.Serialization.TempAssembly..ctor(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace, String location, Evidence evidence)
       at System.Xml.Serialization.XmlSerializer.GenerateTempAssembly(XmlMapping xmlMapping, Type type, String defaultNamespace)
       at System.Xml.Serialization.XmlSerializer..ctor(Type type, String defaultNamespace)
       at System.Xml.Serialization.XmlSerializer..ctor(Type type)
  • Thursday, October 19, 2006 8:46 PM
     
     

     Hey:

     

    I had this same problem.  What happens is that you have duplicate vals in your environment variables-Do this

    IDictionary environmentVariables = Environment.GetEnvironmentVariables();

    DictionaryEntry found = new DictionaryEntry(null, null);

    //Determine how many redundant path varibles there are, should be

    //no more than two, atleast in testing.

    int countPaths = 0;

    foreach (DictionaryEntry de in environmentVariables)

    {

    Console.WriteLine(de.Key.ToString());

    }

    You will see two with the same name, maybe a different case-when the XMLSerializer is created it loads up the env variables into a hash, but apparently runs ToLower() on them, because, in our case, we had Path and PATH, the error said path was attempted to load twice.

    So, what you can do, though a slight hack, is something like this

     

    IDictionary environmentVariables = Environment.GetEnvironmentVariables();

    DictionaryEntry found = new DictionaryEntry(null, null);

    //Determine how many redundant path varibles there are, should be

    //no more than two, atleast in testing.

    int countPaths = 0;

    foreach (DictionaryEntry de in environmentVariables)

    {

    //Did we find a 'path' key, keep count

    if( de.Key.ToString().ToLower().Equals("path") )

    {

    countPaths++;

    //This key, when removed eliminates errors in

    //creating a xml serializer, save it to add back

    //after done

    if(de.Key.ToString().Equals("Path"))

    found = de;

    }

    }

    if( (countPaths > 1) && (found.Key != null) )

    {

    //Temporarily remove the redundant path for this run

    Environment.SetEnvironmentVariable(found.Key.ToString(), null);

    }

    StreamReader reader = new StreamReader(fileName);

    XmlSerializer serializer = new XmlSerializer(typeof(Platform));

    platform = (Platform)serializer.Deserialize(reader.BaseStream);

    reader.Close();

    if( (countPaths > 1) && (found.Key != null) )

    {

    //Add back the path variable removed, for consistency

    Environment.SetEnvironmentVariable(found.Key.ToString(), found.Value.ToString());

    }

    In this case, the problem only showed up when a MAK file called our application-it apparently adds its own Path variable, and so the problem.  I'm not saying this is a great fix-the right fix would be for the XMLSerializer constructor to not call ToLower(). Still, what can you do when a Framework class pukes on its constructor?
  • Monday, November 19, 2007 6:18 PM
     
     
    The problem is duplicate enviromenet variable(not considering case) . Just get rid of them and app will work like a charm

    Is there a hot fix for this?
  • Friday, December 28, 2007 11:37 AM
     
     
    Hi All,

    My build.xml file contains one target that is calling nunit test cases.
    Now, I tried to call build.xml from luntbuild.When I run this project(contaning above build.xml file) from luntbuild,
    It gives me this error: Item has already been added. Key in dictionary: 'path' Key being added: 'path'

    Note: I double checked there is no duplicate entry in enviromenet variable.

    What should i doSad( Please Help

    CASE 1: When I run above build file from command line, it shows me following message:

    C:\Builds\Work>ant
    Buildfile: build.xml

    build:

    NunitCase:
         [exec] NCover.Console v1.5.8 - Code Coverage Analysis for .NET - http://nco
    ver.org
         [exec] Copyright (c) 2004-2006 Peter Waldschmidt


         [exec] Command: nunit-console.exe
         [exec] Command Args: "C:\Documents and Settings\pc185037\My Documents\Visua
    l Studio Projects\Arithmetica.UnitTests\bin\Debug\Arithmetica.UnitTests.dll" "/x
    ml" "c:\coverage\nunitoutput.xml"
         [exec] Working Directory:
         [exec] Assemblies: Arithmetica.UnitTests
         [exec] Coverage Xml: c:\coverage\coverage.xml
         [exec] Coverage Log: c:\coverage\coverage.log

         [exec] Waiting for profiled application to connect...Connected
         [exec] Configuring Profiler...
         [exec] ******************* Program Output *******************
         [exec] NUnit version 2.4.1
         [exec] Copyright (C) 2002-2007 Charlie Poole.
         [exec] Copyright (C) 2002-2004 James W. Newkirk, Michael C. Two, Alexei A.
    Vorontsov.
         [exec] Copyright (C) 2000-2002 Philip Craig.
         [exec] All Rights Reserved.

         [exec] Runtime Environment -
         [exec]    OS Version: Microsoft Windows NT 5.1.2600 Service Pack 2
         [exec]   CLR Version: 2.0.50727.832 ( Net 2.0.50727.832 )

         [exec] ....
         [exec] Tests run: 4, Failures: 0, Not run: 0, Time: 0.516 seconds


         [exec] ***************** End Program Output *****************

    BUILD SUCCESSFUL
    Total time: 7 seconds
    C:\Builds\Work>

    CASE 2: But when I run the above build.xml file from LuntBuild it shows me following error messages in log file:

    Buildfile: C:\Builds\Work\build.xml

    build:

    NunitCase:
         [exec] NCover.Console v1.5.8 - Code Coverage Analysis for .NET - http://ncover.org
         [exec] Copyright (c) 2004-2006 Peter Waldschmidt


         [exec] Command: nunit-console.exe
         [exec] Command Args: "C:\Documents and Settings\pc185037\My Documents\Visual Studio Projects\Arithmetica.UnitTests\bin\Debug\Arithmetica.UnitTests.dll" "/xml" "c:\coverage\nunitoutput.xml"
         [exec] Working Directory:
         [exec] Assemblies: Arithmetica.UnitTests
         [exec] Coverage Xml: c:\coverage\coverage.xml
         [exec] Coverage Log: c:\coverage\coverage.log

         [exec] Item has already been added. Key in dictionary: 'path'  Key being added: 'path'
         [exec] Result: 1

    BUILD SUCCESSFUL
    Total time: 8 seconds
    Duration of the builder(s) execution: 0 minutes
  • Thursday, January 10, 2008 5:28 PM
     
     

    Hello Pooja, I'm one of the Luntbuild developers.  I noticed this post while searching for information on the same problem.

     

    One of our other users is having what seems to be the same problem.  Please see the ideas I posted on our forums:

     

    http://www.javaforge.com/proj/forum/viewMessage.do?thread_id=29858

     

    Thanks.

  • Friday, January 11, 2008 5:11 AM
     
     
    Thanks Jason,

    Actually I have declared the Environment Variables at two places.First under system variables and second under the "Environment Variables" sections of the luntbuild.

    As soon as I removed the Environment Variables from lunt build.My Build executed successully without any error.

    I don't know why does it happens, but I solved the problem in this way only.

    I have few questions regarding this behaviour;

    Que 1: If I am not calling Ncover.exe in my build file, then decalaration of Environment Variables in lunt build is must, other wise build will fail.Why is this dependency?

    Que 2: If I have to call Ncover.exe in my build file, then I have to remove the declaration of Environment Variables from lunt build, other wise build will fail.

    I am confused with this behaviour.

    - Puja
  • Thursday, April 17, 2008 1:52 PM
     
     
    Sorry to resurrect old threads but I'm having a similar problem and to be honest, I dont understand the above posts.

    I'm usually a VB windows app developer and have been asked to create some web forms. I've picked up the microsoft web forms book but have recieved this error at the first hurdle. I havent added any text, just created a brand new "ASP.Net web site" application and hit run. I get this error and I'm using VS2008.

    Any help would be greatly appreciated.
  • Thursday, April 17, 2008 4:31 PM
     
     

    Start Here:

     

    Start->Control Panel->Setting->System->Advanced->Environment Variables

     

    Look at your list and see if you have any two entries with the same text but different case.  If so, first record what they are, then change one of them to a different text and retry your app.  Obviously you will want to find out what the purpose of that variable is in your environment before leaving it that way long term.

     

    Otherwise, try to catch  the error and post the StackTrace from it here-put a try catch in the Program.cs Main function.

  • Thursday, April 17, 2008 6:10 PM
     
     
    Thanks for that - I checked the lists and couldnt find any duplicates so it's not that.

    The stack trace that it shows in the browser when I try to run the code is below:
    [ArgumentException: Item has already been added. Key in dictionary: 'path'  Key being added: 'path']
    System.Collections.Hashtable.Insert(Object key, Object nvalue, Boolean add) +2904181
    System.Collections.Hashtable.Add(Object key, Object value) +11
    System.Collections.Specialized.StringDictionary.Add(String key, String value) +61
    System.CodeDom.Compiler.Executor.ExecWaitWithCaptureUnimpersonated(SafeUserTokenHandle userToken, String cmd, String currentDir, TempFileCollection tempFiles, String& outputName, String& errorName, String trueCmdLine) +789
    System.CodeDom.Compiler.Executor.ExecWaitWithCapture(SafeUserTokenHandle userToken, String cmd, String currentDir, TempFileCollection tempFiles, String& outputName, String& errorName, String trueCmdLine) +111
    System.CodeDom.Compiler.CodeCompiler.Compile(CompilerParameters options, String compilerDirectory, String compilerExe, String arguments, String& outputFile, Int32& nativeReturnValue, String trueArgs) +457
    Microsoft.VisualBasic.VBCodeGenerator.FromFileBatch(CompilerParameters options, String[] fileNames) +589
    System.CodeDom.Compiler.CodeCompiler.System.CodeDom.Compiler.ICodeCompiler.CompileAssemblyFromFileBatch(CompilerParameters options, String[] fileNames) +188
    System.CodeDom.Compiler.CodeDomProvider.CompileAssemblyFromFile(CompilerParameters options, String[] fileNames) +23
    System.Web.Compilation.AssemblyBuilder.Compile() +843
    System.Web.Compilation.BuildProvidersCompiler.PerformBuild() +164
    System.Web.Compilation.BuildManager.CompileWebFile(VirtualPath virtualPath) +267
    System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile) +582
    System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile) +93
    System.Web.Compilation.BuildManager.GetVirtualPathObjectFactory(VirtualPath virtualPath, HttpContext context, Boolean allowCrossApp, Boolean noAssert) +111
    System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(VirtualPath virtualPath, Type requiredBaseType, HttpContext context, Boolean allowCrossApp, Boolean noAssert) +54
    System.Web.UI.PageHandlerFactory.GetHandlerHelper(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath) +31
    System.Web.UI.PageHandlerFactory.System.Web.IHttpHandlerFactory2.GetHandler(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath) +40
    System.Web.HttpApplication.MapHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig) +139
    System.Web.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +128
    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +161
    If this isnt what you wanted then I had a go at the try/catch you asked for. I didnt have any luck working out where it went though. I tried to put it in the page load event but it didnt fire.

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Try
                MsgBox("help")
            Catch ex As Exception
                Debug.Print(ex.Message)
                Debug.Print(ex.StackTrace)
            End Try
        End Sub

    Like I said before, I'm totally new to web forms so you'll have to bear with me. Sorry!
  • Thursday, April 17, 2008 6:32 PM
     
     

    Tonylad:

     

    OK,

     

    In looking at the error path it looks so much like you have two instances of PATH.  Not saying I don't believe you-maybe for some unknown reason Windows is not showing you this.

     

    Create a new C# project, choose Console Application for the type, then totally replace the contents of Program.cs with the following, build, run through debugger and send the results that come out in the Output window below.

     

    My results are this:

     

    ********* INSTANCE OF PATH IN YOUR ENVIRONMENT**************

    Path

     

    // Code

     

    using System;

    using System.Collections.Generic;

    using System.Text;

    using System.Collections;

    using System.Diagnostics;

    namespace EnviroExaminer

    {

    class Program

    {

    static void Main(string[] args)

    {

    IDictionary environmentVariables = Environment.GetEnvironmentVariables();

    DictionaryEntry found = new DictionaryEntry(null, null);

    int countPaths = 0;

    Debug.WriteLine("********* INSTANCE OF PATH IN YOUR ENVIRONMENT**************");

    foreach (DictionaryEntry de in environmentVariables)

    {

    if (de.Key.ToString().ToLower().Equals("path"))

    {

    Debug.WriteLine(de.Key);

    }

    }

    }

    }

    }

     

     

  • Thursday, April 17, 2008 6:59 PM
     
     
    Well after baby stepping me through it, I managed to run my first C# application!

    But alas, I get the same as you. It only finds one instance of Path.

    ********* INSTANCE OF PATH IN YOUR ENVIRONMENT**************
    path


    If it's any more information for you, here's the value of path in my environment variables"

    C:\oracle\ora92\bin;C:\Program Files\Oracle\jre\1.3.1\bin;C:\Program Files\Oracle\jre\1.1.8\bin;C:\Program Files\QuickTime\QTSystem\

    And there's something similar called PATHEXT with a value of .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH

    And another one called CLASSPATH and it's value is .;C:\Program Files\Java\jre1.6.0_03\lib\ext\QTJava.zip
  • Thursday, April 17, 2008 7:29 PM
     
     

    Huh.

     

    Well, let's take a step back-from what I read this is just the stock application that Visual Studio creates for you?  You just had the wizard walk you through the steps, then tried to run it?  Or if not, what did you add?

     

  • Thursday, April 17, 2008 7:31 PM
     
     

    Also, did you read this post:

     

    If I run the application by clicking on the exe then no errors, but if I run it within VS2005. it throws me this exception which I have no idea why its doing. Interestingly this only happens on my Windows 2000 professional machine, same code if I run on Windows XP Professional, it works like a charm.

    Exception:
    Item has already been added. Key in dictionary: 'path'  Key being added: 'path'

    Please update with a work around.

    Syed Hussain

     

     

    Is this the case for you-does it work if you compile to release and run that way?

  • Thursday, April 17, 2008 7:53 PM
     
     
    Ok, I was walking through the brand new file steps and managed to get a new file to work - so whatever I had been doing today seems to have worked.

    The file I was working on still wouldnt work - same error message. So what I've done is copied across the default.aspx file to a brand new (working) project and it seems to do the trick.

    I don't know what I've done but lets hope it doesnt appear again. Thanks for your help, let's hope I dont have to post again in a few days!
  • Friday, April 18, 2008 1:50 PM
     
     
    Well the few days I mentioned before was right, I didnt even manage 24 hours before it reared its ugly head again - the exact same error message. First thing I did was to check for 2 instances of path to see if it was creating them randomly and it wasnt that.

    I was able to start a new project without any problems so I decided to try to release it to see if that worked as per your previous post. Well it didnt load but I had a different error message (see below).

    I suppose I could do what I did yesterday and copy the files to a new project, but its a bit crazyto have to do that all the time.

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

    Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.

    Parser Error Message: Unrecognized attribute 'type'.

    Source Error:

    Line 2:  <configuration>
    Line 3: <configSections>
    Line 4: <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
    Line 5: <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
    Line 6: <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>


  • Friday, April 18, 2008 6:19 PM
     
     
    Well after hours and hours of messing around, i finally managed to run the application outside of visual studio.

    I installed IIS - fixed that (also wasnt working correctly), and published my website to my local machine (acting like a server) and that seems to work OK. Saying that, it still doesnt work through visual studio 2008 - same error as always.

    Now I can continue to work in the mean time but it's not really feasible for the VS run command to not work.

    Any more ideas anyone?
  • Wednesday, April 23, 2008 7:21 AM
     
     
    Hey all,

    just to complement Tyler's descriptions, here is what I found out:

    As you can see in the stack traces the issue does not come from an XML component. Instead, the function System.CodeDom.Compiler.Executor.ExecWaitWithCaptureUnimpersonated(...) adds the duplicate key to the hash table. If you look at the published .NET runtime sources (e.g. here online), you actually find the following snippet in the implementation:

    //
    // Prepare the environment
    //
    #if PLATFORM_UNIX
    StringDictionary environment = new CaseSensitiveStringDictionary();
    #else
    StringDictionary environment = new StringDictionary();
    #endif // PLATFORM_UNIX
                   
    // Add the current environment
    foreach (DictionaryEntry entry in Environment.GetEnvironmentVariables())
        environment.Add((string)entry.Key, (string)entry.Value);


    Since we are talking about a non-Unix build, the case-insensitive StringDictionary is used, leading to the hash-table exception we experience in case of duplicate environment variable names with different capitalization.

    Mike

  • Friday, May 28, 2010 5:23 PM
     
     Proposed Answer

    El error se me presentó cuando actualicé el archivo de recursos_PT.resx en la aplicación CMS. Lo solucioné actualizando todos los archivos de recursos, controles y el dll de la aplicación, y por último IISRESET y listo.

     

     

    • Proposed As Answer by liches Friday, May 28, 2010 5:24 PM
    •