Меню

The given key was not present in the dictionary ошибка

This article applies to Microsoft Dynamics AX for all regions.

Symptoms

When you try to validate a product configuration model that has a system level table constraint in Microsoft Dynamics AX 2012, you receive the following error message:

The given key was not present in the dictionary.

Resolution

Hotfix information

A supported hotfix is available from Microsoft. There is a «Hotfix Download Available» section at the top of this Knowledge Base article. If you are encountering an issue downloading, installing this hotfix, or have other technical support questions, contact your partner or, if enrolled in a support plan directly with Microsoft, you can contact technical support for Microsoft Dynamics and create a new support request. To do this, visit the following Microsoft website:

https://mbs.microsoft.com/support/newstart.aspx You can also contact technical support for Microsoft Dynamics by phone using these links for country specific phone numbers. To do this, visit one of the following Microsoft websites:

Partners

https://mbs.microsoft.com/partnersource/support/Customers

Installation information

If you have customizations for one or more of the methods or the tables that are affected by this hotfix, you must follow these steps:

  1. Review the changes that are documented in the .xpo file.

  2. Apply these changes in a test environment before you apply the hotfix in a production environment.

For more information about how to install this hotfix, click the following article number to view the article in the Microsoft Knowledge Base:

893082 How to install a Microsoft Dynamics AX hotfix

Prerequisites

You must have Microsoft Dynamics AX 2012 installed to apply this hotfix.

Restart requirement

You must restart the Application Object Server (AOS) service after you apply the hotfix.

File information

The global version of this hotfix has the file attributes (or later file attributes) that are listed in the following table. The dates and times for these files are listed in Coordinated Universal Time (UTC). When you view the file information, it is converted to local time. To find the difference between UTC and local time, use the Time Zone tab in the Date and Time item in Control Panel.

File name

File version

File size

Date

Time

Platform

Aximpactanalysis.exe

Not applicable

60,280

22-May-2012

02:09

x86

Axupdate.exe

Not applicable

60,264

22-May-2012

02:09

x86

Dynamicsax2012-kb2726435-extensions.axmodel

6.1.1108.1311

224,536

21-Jun-2012

08:36

Not applicable

Dynamicsax2012-kb2726435-foundation.axmodel

6.0.1108.1311

260,888

21-Jun-2012

08:36

Not applicable

Dynamicsax2012-kb2726435-fpplabels.axmodel

6.0.1108.1311

194,840

21-Jun-2012

08:36

Not applicable

Dynamicsax2012-kb2726435-syplabels.axmodel

6.0.1108.1311

895,272

21-Jun-2012

08:36

Not applicable

Axsetupsp.exe

6.0.947.853

1,361,768

22-May-2012

02:09

x86

Axutillib.dll

6.0.1108.806

821,480

22-May-2012

02:09

x86

Microsoft.dynamics.servicing.operations.dll

6.0.888.436

35,752

22-May-2012

02:09

x86

Axsetupsp.resources.dll

6.0.947.491

382,848

22-May-2012

02:09

x86

Axsetupsp.resources.dll

6.0.947.491

370,560

22-May-2012

02:09

x86

Axsetupsp.resources.dll

6.0.947.491

374,656

22-May-2012

02:09

x86

Axsetupsp.resources.dll

6.0.947.491

374,656

22-May-2012

02:09

x86

Axsetupsp.resources.dll

6.0.947.491

370,560

22-May-2012

02:09

x86

Axsetupsp.resources.dll

6.0.947.491

378,752

22-May-2012

02:09

x86

Axsetupsp.resources.dll

6.0.947.491

370,560

22-May-2012

02:09

x86

Axsetupsp.resources.dll

6.0.947.491

374,656

22-May-2012

02:09

x86

Axsetupsp.resources.dll

6.0.947.491

370,560

22-May-2012

02:09

x86

Axsetupsp.resources.dll

6.0.947.491

374,656

22-May-2012

02:09

x86

Axsetupsp.resources.dll

6.0.947.491

370,560

22-May-2012

02:09

x86

Axsetupsp.resources.dll

6.0.947.491

407,424

22-May-2012

02:09

x86

Status

Microsoft has confirmed that this is a problem in the Microsoft products that are listed in the «Applies to» section.

Note This is a «FAST PUBLISH» article created directly from within the Microsoft support organization. The information contained herein is provided as-is in response to emerging issues. As a result of the speed in making it available, the materials may include typographical errors and may be revised at any time without notice. See Terms of Use for other considerations.

Need more help?

  • Remove From My Forums
  • Question

  • I am using following code to filter out some data from one datatable to another

    if (dtKeys.Rows.Count > 0 && objEntryPlanningReport.PostageCalculationTable != null && objEntryPlanningReport.PostageCalculationTable.Rows.Count > 0)
                {
                    dt = objEntryPlanningReport.PostageCalculationTable.Clone();//cloning the structure
                    try
                    {
                        foreach (DataRow dr in dtKeys.Rows)
                        {
                            DataView datavw = new DataView();
                            datavw = objEntryPlanningReport.PostageCalculationTable.DefaultView;//Getting the default view
                            datavw.RowFilter = " JobID = '" + dr["fkJobID"].ToString() + "' and fkContainerID='" + dr["csmContainerID"].ToString() + "' "; //filter out the data i wanted to extract
    
                            if (datavw.Count > 0)
                            {
                                foreach (DataRow drMatched in datavw.ToTable().Rows)//error in this line.The given key was not present in the dictionary.
                                {
                                    dt.ImportRow(drMatched);//copying the matched rows in my desired table
                                }
                            }                       
                        }
                    }
                    catch (Exception ex)
                    {
                        
                        //throw;
                    }
                    dt.AcceptChanges();
                }
                return dt;

    But On random basis On the line I have highlighted I am getting following error

    The given key was not present in the dictionary.

    How can i avoid it


    Kamran Shahid Principle Engineer Development (MCP,MCAD,MCSD.NET,MCTS,MCPD.net[web])

Answers

  • This is not really an «exception», it’s just a problem with the debugger. The debugger attempted to get the Capacity of thet able, but it took too long, so it aborted the attempt. Usually that just means the computer doesn’t have enough resources to do everything
    it needs to do within the time that Visual Studio allows. 

    I would recommend looping through dr directly (instead of the view). Add dr[«fkJobID»] and dr[«csmContainerID»] to your Waches window, and put a breakpoint somewhere in your loop. Keep hitting F5 until you see where one of those two calls returns an exception
    instead of a legitimate value.


    Check out
    My Blog. Now updated to actually work!

    • Marked as answer by

      Wednesday, May 9, 2012 3:34 AM

An System.Collections.Generic.KeyNotFoundException “The given key was not present in the dictionary” can be the result of using a too old MySQL Connector/NET version in your ASP.NET web application. A KeyNotFoundException is thrown when an operation attempts to retrieve an element from a collection using a key that does not exist in that collection. An unsupported character set like utf8mb4 can be such a key, if your Connector/NET doesn’t support this character set. Luckily there is an easy workaround for this.

MySQL (Oracle) Connector/NET versions prior to 6.0.8, 6.1.6, 6.2.5, 6.3.6 lack a mapping for UTF8MB4 as charset. Connecting to a MySQL database and querying a table that has been created with CHARSET=utf8mb4 results in a .NET exception:

Exception Details: System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.

System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary. at System.Collections.Generic.Dictionary`2.get_Item(TKey key) at MySql.Data.MySqlClient.CharSetMap.GetCharacterSet(DBVersion version, String CharSetName) at MySql.Data.MySqlClient.CharSetMap.GetEncoding(DBVersion version, String CharSetName) at MySql.Data.MySqlClient.Driver.Configure(MySqlConnection connection) at MySql.Data.MySqlClient.MySqlConnection.Open() at ASP.mysql_data_aspx.MySQLConn()

A more extended exception is:

System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary. at System.Collections.Generic.Dictionary`2.get_Item(TKey key) at MySql.Data.MySqlClient.CharSetMap.GetCharacterSet(DBVersion version, String CharSetName) at MySql.Data.MySqlClient.MySqlField.SetFieldEncoding() at MySql.Data.MySqlClient.NativeDriver.GetColumnData(MySqlField field) at MySql.Data.MySqlClient.NativeDriver.GetColumnsData(MySqlField[] columns) at MySql.Data.MySqlClient.Driver.GetColumns(Int32 count) at MySql.Data.MySqlClient.ResultSet.LoadColumns(Int32 numCols) at MySql.Data.MySqlClient.ResultSet..ctor(Driver d, Int32 statementId, Int32 numCols) at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId) at MySql.Data.MySqlClient.MySqlDataReader.NextResult() at MySql.Data.MySqlClient.MySqlDataReader.Close() at MySql.Data.MySqlClient.MySqlCommand.ResetReader() at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior) at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader() at ASP.mysql_data_aspx.MySQLConn()

Googling for a fix, some suggestions were to add CharSet=utf8; to your connection string. Unfortunately I was unable to resolve the exception with this added.

The best way to fix this System.Collections.Generic.KeyNotFoundException with Connector/NET is to simply update your Connector/NET version. Support for utf8mb4 charset is built in in versions 6.0.8, 6.1.6, 6.2.5, 6.3.6+:

MySQL Connector/NET did not support the utf8mb4 character set. When attempting to connect to utf8mb4 tables or columns, an exception KeyNotFoundException was generated. (Bug #58244)

https://dev.mysql.com/doc/relnotes/connector-net/en/news-6-0-8.html

And MySQL Connector/NET now supports MySQL servers configured to use utf8mb4 as the default character set in version 8.0.9.

MySQL Connector/NET now supports MySQL servers configured to use utf8mb4 as the default character set.

https://dev.mysql.com/doc/relnotes/connector-net/en/news-8-0-9.html

If, for some reason, you cannot or will not update your MySQL Connector/NET version anytime soon, there is an easy workaround available; SET NAMES 'utf8'. Yes, that’s right: as your first statement, set the three session system variables

  • character_set_client
  • character_set_connection
  • character_set_results

to the given character set utf8. You can even use latin1, but that may give some undesired encoding issues…

Imaging the following C# MySql.Data.MySqlClient test script for querying your MySQL database table:

string sql = "select * from aspnet_site_comments"; MySqlCommand cmd = new MySqlCommand(sql, conn); MySqlDataReader rdr = cmd.ExecuteReader(); while (rdr.Read()) { Response.Write(rdr[0]+ "<br/>"); } rdr.Close(); } catch (Exception ex) { Response.Write(ex.ToString()); }

Code language: C# (cs)

Are you looking for rock solid, eco-friendly, .NET hosting? Look no further! UmbHost offers powerful hosting services for websites and businesses of all sizes, and is powered by 100% renewable energy!

If your MySQL database server has in its my.cnf server config:

character_set_server utf8mb4 collation_server = utf8mb4_unicode_ci

Code language: SQL (Structured Query Language) (sql)

And your table aspnet_site_comments is created using ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci, it throws an System.Collections.Generic.KeyNotFoundException exception. Alter your code to first set the character_set_* to utf8 (don’t mind my pseudo-code, you’ll get the idea) as a workaround for this issue:

string setcharset = "SET NAMES 'utf8'"; // <-- !! MySqlCommand charsetcmd = new MySqlCommand(setcharset, conn); MySqlDataReader charsetrdr = charsetcmd.ExecuteReader(); charsetrdr.Close() string sql = "select * from aspnet_site_comments"; MySqlCommand cmd = new MySqlCommand(sql, conn); MySqlDataReader rdr = cmd.ExecuteReader(); while (rdr.Read()) { Response.Write(rdr[0]+ "<br/>"); } rdr.Close(); } catch (Exception ex) { Response.Write(ex.ToString()); }

Code language: C# (cs)

Only use this as a temporary fix, you should still update Connector/NET ASAP. That’s it!

  • Remove From My Forums
  • Question

  • When i click site columns in Site Settings.

    I got an error message.

    The given key was not present in the dictionary.

Answers

  • I too exhausted every option to delete those bad columns that were referencing a deleted field type. Since this was on a dev. SharePoint farm, I ended up going after the SQL content database.
    Had this been a production environment, I would have stopped and called MS support.

    First I wrote a small C# console application to identify the offending field Ids. The code simply outputs the SchemaXml property of the root web AvailableFields property. I then searched the output for the name of the deleted field type, and made
    note of the field Ids for those fields that are of the deleted field type.

    Now on to the SQL Management Studio. The table of interest is the ContentType table. I first ran a SQL command against the table looking for the offending Ids. SELECT * FROM ContentTypes WHERE Definition Like (‘%xxx-xxx-xxx-xxx-xxx%’). That returned back
    the actual field type references that SharePoint was still hanging on to. I then ran a SQL DELETE command against those rows to get rid of them.

    The Site Columns link on the site settings page finally started to work and SharePoint is happy again, for good I hope.

    • Proposed as answer by

      Tuesday, August 31, 2010 4:23 PM

    • Marked as answer by
      Mike Walsh FIN
      Monday, December 6, 2010 12:21 PM

How to fix Veeam VM replication error ‘The given key was not present in the dictionary.’

Recently I’ve been getting an error on one of my replication jobs in one of our Veeam environments. The error message was a bit vague, and to be honest, I’ve never seen it anywhere behore. The error message was:

The given key was not present in the dictionary.

Veeam the given key was not present in the dictionary

Veeam error ‘The given key was not present in the dictionary.’

If you browse to your log file location, usually under:

C:ProgramDataVeeamBackup%JOBNAME%

You can find a more detailed error message like the one below:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

&#91;11.09.2019 21:06:28] &lt;181&gt; Info     [SnapReplicaVmTarget] Getting disk ‘2006’ datastore from DatastoreMap

&#91;11.09.2019 21:06:28] &lt;181&gt; Error    The given key was not present in the dictionary. (System.Collections.Generic.KeyNotFoundException)

&#91;11.09.2019 21:06:28] &lt;181&gt; Error       at System.ThrowHelper.ThrowKeyNotFoundException()

&#91;11.09.2019 21:06:28] &lt;181&gt; Error       at System.Collections.Generic.Dictionary`2.get_Item(TKey key)

&#91;11.09.2019 21:06:28] &lt;181&gt; Error       at Veeam.Backup.Core.CViSnapReplicaVmTargetDatastoreMap.GetDiskDatastoreFromMap(Int32 diskKey)

&#91;11.09.2019 21:06:28] &lt;181&gt; Error       at Veeam.Backup.Core.CViSnapReplicaVmTarget.SyncDisks(IEnumerable`1 diskBackupObjects, CViReplicaProfilesResolver profilesResolver)

&#91;11.09.2019 21:06:28] &lt;181&gt; Error       at Veeam.Backup.Core.CViSnapReplicaVmTarget.PrepareConfig(CBackupClient sourceClient, CBackupObjectsCollection backupCollection, CViSnapReplicaVm replicaVm)

&#91;11.09.2019 21:06:28] &lt;181&gt; Error       at Veeam.Backup.Core.CViSnapReplicaVmTarget.ProcessConfig(CBackupClient sourceClient, CBackupSet backupSet)

&#91;11.09.2019 21:06:28] &lt;181&gt; Error    The given key was not present in the dictionary. (System.Collections.Generic.KeyNotFoundException)

&#91;11.09.2019 21:06:28] &lt;181&gt; Error       at System.ThrowHelper.ThrowKeyNotFoundException()

&#91;11.09.2019 21:06:28] &lt;181&gt; Error       at System.Collections.Generic.Dictionary`2.get_Item(TKey key)

&#91;11.09.2019 21:06:28] &lt;181&gt; Error       at Veeam.Backup.Core.CViSnapReplicaVmTargetDatastoreMap.GetDiskDatastoreFromMap(Int32 diskKey)

&#91;11.09.2019 21:06:28] &lt;181&gt; Error       at Veeam.Backup.Core.CViSnapReplicaVmTarget.SyncDisks(IEnumerable`1 diskBackupObjects, CViReplicaProfilesResolver profilesResolver)

&#91;11.09.2019 21:06:28] &lt;181&gt; Error       at Veeam.Backup.Core.CViSnapReplicaVmTarget.PrepareConfig(CBackupClient sourceClient, CBackupObjectsCollection backupCollection, CViSnapReplicaVm replicaVm)

&#91;11.09.2019 21:06:28] &lt;181&gt; Error       at Veeam.Backup.Core.CViSnapReplicaVmTarget.ProcessConfig(CBackupClient sourceClient, CBackupSet backupSet)

&#91;11.09.2019 21:06:28] &lt;181&gt; Info         [AgentsSession] Disposing…

And however vague this error message is, this is it. There are no other log entries anywhere else in the system that could help out more. Just for the records of this issue, this environment is running Veeam version: 9.5 U3a.

After researching this error, I have found only four results on the web that could possibly help me, but none of them helped me out. One suggestion was that the SSO/PSC connection to the vCenter was faulty. However, this was not the case because we have several other replication jobs running on the same vCenter without any issues. The other solution from another blogger had something to do with permissions on a dvSwitch that were missing in his case. Nevertheless, this also is not the case for us for the same reason as I have mentioned before.

So, what did help? Well, I did a few things but the key thing I did was to delete the configuration entry of this virtual machine from the Veeam database. This is actually a rather silly step to execute, but I’m guessing the value for the virtual disks in the Veeam database were corrupted somehow. You can easily do this from the Veeam GUI following the next couple of steps:

  1. Login to
    your Veeam environment.
  2. Go to your
    backup or replica under ‘Backups’ or ‘Replicas’.
  3. Search and
    find the virtual machine that is giving this error.
  4. Right
    click this VM and select ‘Remove from configuration’.
  5. Go back to
    your backup or replica job.
  6. Re-configure
    the virtual machine in the backup or replication job.
  7. Re-run the
    backup or replication job.

That’s it, after this your backup or replication job should work again. One thing you can also do is to rescan your vCenters so that the Veeam database gets populated with new entries that could be missing. The good thing about this solution is that you do not even have to do a remapping of the replica virtual machine to the job. This happens automatically. I also did not have any ‘hash recalculation’ jobs for this replica once the fix was applied. Which Veeam usually does when something happened to a replica.

Veeam the given key was not present in the dictionary

Veeam working replication job after fix

Applying the fix for
the error also meant that we didn’t have to re-do the full replication for this
virtual machine. Normally I would’ve just thrown away the replica VM and
replicated the VM again, but since this was a very large machine this just
wasn’t an option.

I hope this helps anybody that is having this issue!

**Edited and updated with new findings on 2020-01-04.



This C# exception article demonstrates the KeyNotFoundException.

KeyNotFoundException. A KeyNotFoundException was thrown.

This is likely caused by an invalid usage of the Dictionary collection. As always we want a quick way to fix the problem. We look at correct and incorrect examples.

Example. First, here we see some code that looks correct. But it has a severe flaw. This is the problem: you cannot look up a key that is not found in the Dictionary and try to assign your variable to its value.

Here: The KeyNotFoundException is thrown on the final line of try-block. The string «test» is not present in the collection.

TryCatch

C# program that throws KeyNotFoundException

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	try
	{
	    //
	    // Create new Dictionary with string key of "one"
	    //
	    Dictionary<string, string> test = new Dictionary<string, string>();
	    test.Add("one", "value");

	    //
	    // Try to access key of "two"
	    //
	    string value = test["two"];
	}
	catch (Exception ex)
	{
	    //
	    // An exception will be thrown.
	    //
	    Console.WriteLine(ex);
	}
    }
}

Output

System.Collections.Generic.KeyNotFoundException:
    The given key was not present in the dictionary.
at System.ThrowHelper.ThrowKeyNotFoundException()
...

Example 2. We can fix this exception by using the TryGetValue method on the Dictionary constructed type. Note that could use ContainsKey instead of TryGetValue, but the below code preserves the intention of the previous code.

ContainsKeyTryGetValue

C# program that does not throw

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	Dictionary<string, string> test = new Dictionary<string, string>();
	test.Add("one", "value");
	//
	// Use TryGetValue to avoid KeyNotFoundException.
	//
	string value;
	if (test.TryGetValue("two", out value))
	{
	    Console.WriteLine("Found");
	}
	else
	{
	    Console.WriteLine("Not found");
	}
    }
}

Output

Not found

You always have to use the if-statement when testing values in the Dictionary, because there is always a possibility that the key will not exist. The C# compiler cannot detect missing keys. They can only be detected at runtime.

Tester-DoerCompile-Time Error

Summary. We saw how to raise and catch the KeyNotFoundException during runtime. We then saw how to avoid causing the exception. We discussed alternatives, such as TryGetValue and ContainsKey, and looked at a program that does not have this problem.


Related Links

Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • The game has crashed hitman 2 как исправить ошибку
  • The game cannot be launched синтаксическая ошибка prince of persia