An item with the same key has already been added error in ASP.NET MVC 5 - asp.net-mvc-5

I'm upgrading an ASP.NET MVC 3 project to MVC 5 (VS 2017) and i have the below line of code
IEnumerable<Country> countrydata = _db.Country.OrderBy(s => s.CountryName).ToList();
That line of code works fine in MVC 3 (in a .NET 4 project) but throws the below error in MVC 5 project targeting .NET 4.6.1, does anybody see why?
An item with the same key has already been added
UPDATE:
After further testing, it seems like all such calls to the database will fail in MVC 5 / Entity Framework 6, because even the below line fails with the same error message.
IEnumerable<AuthenticationType> authenticationProvider = _db.AuthenticationType.OrderBy(n => uthenticationProvider).ToList();
#Christos, see the .edmx designer message i mention below
Below is the stack trace
at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) at System.Collections.Generic.Dictionary2.Insert(TKey key, TValue value, Boolean add) at System.Data.Metadata.Edm.ObjectItemAttributeAssemblyLoader.LoadRelationshipTypes() at System.Data.Metadata.Edm.ObjectItemAttributeAssemblyLoader.LoadTypesFromAssembly() at System.Data.Metadata.Edm.ObjectItemAssemblyLoader.Load() at System.Data.Metadata.Edm.ObjectItemAttributeAssemblyLoader.Load() at System.Data.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly assembly, Boolean loadReferencedAssemblies, ObjectItemLoadingSessionData loadingData) at System.Data.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly assembly, Boolean loadReferencedAssemblies, KnownAssembliesSet knownAssemblies, EdmItemCollection edmItemCollection, Action1 logLoadMessage, Object& loaderCookie, Dictionary2& typesInLoading, List1& errors) at System.Data.Metadata.Edm.ObjectItemCollection.LoadAssemblyFromCache(ObjectItemCollection objectItemCollection, Assembly assembly, Boolean loadReferencedAssemblies, EdmItemCollection edmItemCollection, Action`1 logLoadMessage) at System.Data.Metadata.Edm.ObjectItemCollection.ImplicitLoadAssemblyForType(Type type, EdmItemCollection edmItemCollection) at System.Data.Metadata.Edm.MetadataWorkspace.ImplicitLoadAssemblyForType(Type type, Assembly callingAssembly) at System.Data.Objects.ObjectContext.GetTypeUsage(Type entityCLRType) at System.Data.Objects.ObjectContext.GetEntitySetForNameAndType(String entitySetName, Type entityCLRType, String exceptionParameterName) at System.Data.Objects.ObjectContext.CreateObjectSet[TEntity](String entitySetName) at SSAMapper.Models.SSAMapperEntities.get_Country() in D:\Projects\SSAMapper\Models\SSAMapper.Designer.cs:line 240 at SSAMapper.Models.AdminModel.GetCountries(Boolean status, Boolean userCountry, Boolean loadDeactivatedCountry) in D:\Projects\SSAMapper\Models\AdminModel.cs:line 1116

I'm leaning towards it being the upgrade to Entity Framework 6 gone awry. It's using lazy loading, and you've removed .ToList() so the exception is thrown prior to any data access. We can see in the stack trace it's during creation of the ObjectSet<TEntity> and if I'm understanding it correctly, it looks to be when looking at relationships to make sure the assembly for their types are loaded.
I would look at the <NavigationProperty>s on the conceptual model in the .edmx and see if there appears to be any duplicates. It seems like it could also happen if you have duplicated model classes in your project or if any of the model classes are defined in more than one assembly in your bin (like if you renamed your project/target assembly but the original dll is still there).
Here are a couple links that may be useful: Upgrading to Entity Framework 6 I would go through that and make sure nothing was missed. And here was a question with the same error with the source code involved shown.

Related

Kentico upgrade 10 to 11 - CMSDataVersion upgrade failure

I used the upgrade100_110.exe tool to upgrade my Kentico 10 CMS solution. The solution and database schema were successfully upgraded, but upon accessing the site's admin portal in a web browser, the expected data upgrade did not occur.
To clarify, the CMSSettingsKey KeyValue for CMSDBVersion is 11.0, but the CMSSettingsKey KeyValue for CMSDataVersion is still 10.0.
The only UPGRADE events in the Kentico event log are the following:
Message: 'system' is a duplicate attribute name. Line 1, position 5202.
Exception type: System.Xml.XmlException Stack trace: at
System.Xml.XmlTextReaderImpl.Throw(Exception e) at
System.Xml.XmlTextReaderImpl.AttributeDuplCheck() at
System.Xml.XmlTextReaderImpl.ParseAttributes() at
System.Xml.XmlTextReaderImpl.ParseElement() at
System.Xml.XmlTextReaderImpl.ParseElementContent() at
System.Xml.XmlTextReaderImpl.Read() at
System.Xml.XmlLoader.LoadNode(Boolean skipOverWhitespace) at
System.Xml.XmlLoader.LoadDocSequence(XmlDocument parentDoc) at
System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean
preserveWhitespace) at System.Xml.XmlDocument.Load(XmlReader
reader) at System.Xml.XmlDocument.LoadXml(String xml) at
CMS.FormEngine.FormHelper.MergeFormDefinitions(String original, String
alternative, Boolean includeAllAltFields) at
UpgradeProcedure.UpdateAlternativeForms() at
UpgradeProcedure.UpgradeApplication(Func`1 versionSpecificMethod,
String newVersion, String packageName) at UpgradeProcedure.Update()
and
Message: 'system' is a duplicate attribute name. Line 1, position
5202.
Exception type: System.Xml.XmlException Stack trace: at
System.Xml.XmlTextReaderImpl.Throw(Exception e) at
System.Xml.XmlTextReaderImpl.AttributeDuplCheck() at
System.Xml.XmlTextReaderImpl.ParseAttributes() at
System.Xml.XmlTextReaderImpl.ParseElement() at
System.Xml.XmlTextReaderImpl.ParseElementContent() at
System.Xml.XmlLoader.LoadNode(Boolean skipOverWhitespace) at
System.Xml.XmlLoader.LoadDocSequence(XmlDocument parentDoc) at
System.Xml.XmlDocument.Load(XmlReader reader) at
System.Xml.XmlDocument.LoadXml(String xml) at
CMS.FormEngine.FormHelper.MergeFormDefinitions(String original, String
alternative, Boolean includeAllAltFields) at
UpgradeProcedure.UpdateAlternativeForms() at
UpgradeProcedure.UpgradeApplication(Func`1 versionSpecificMethod,
String newVersion, String packageName) at UpgradeProcedure.Update()
I'm looking for suggestions on how to troubleshoot this problem. Any suggestions on where to start would be helpful!
Are there any custom modules or modules from marketplace? I've seen an issue where this error had been caused by the URL Redirection module. https://devnet.kentico.com/articles/url-redirection
Or, another idea: MergeFormDefinitions will merge upgraded form definitions with previous ones to transfer custom fields to new forms.
It seems like one of the old forms is not stored correctly and the XML definitions are containing system elements twice. Or, it contains a field called like this which could be a reserved word.
You can check the definitions in the CMS_Calss table to see it contains a element.
Alternatively, you can add a breakpoint into the upgrade procedure to catch the temp table. Then you will be able to see the new definitions and compare them. These two are being merged later and it seems the issue occurs at that time.

Error after upgrading to Azure Mobile Services 1.3.1

I have a Xamarin.iOS project and recently upgraded that plus my PCL project to have Windows Azure Mobile Services SDK 1.3.1.
However I now get an error when it tries to create a new MobileServiceClient.
{System.NullReferenceException: Object reference not set to an instance an object
at Microsoft.WindowsAzure.MobileServices.MobileServiceHttpClient.GetUserAgentHeader () [0x0002e] in d:\jw\ZumoSDKBuild_Dev\source\sdk\Managed\src\Microsoft.WindowsAzure.MobileServices\Http\MobileServiceHttpClient.cs:683
at Microsoft.WindowsAzure.MobileServices.MobileServiceHttpClient..ctor (IEnumerable`1 handlers, System.Uri applicationUri, System.String installationId, System.String applicationKey) [0x0004e] in d:\jw\ZumoSDKBuild_Dev\source\sdk\Managed\src\Microsoft.WindowsAzure.MobileServices\Http\MobileServiceHttpClient.cs:138
at Microsoft.WindowsAzure.MobileServices.MobileServiceClient..ctor (System.Uri applicationUri, System.String applicationKey, System.Net.Http.HttpMessageHandler[] handlers) [0x00040] in d:\jw\ZumoSDKBuild_Dev\source\sdk\Managed\src\Microsoft.WindowsAzure.MobileServices\MobileServiceClient.cs:199
at Microsoft.WindowsAzure.MobileServices.MobileServiceClient..ctor (System.Uri applicationUri, System.String applicationKey) [0x00000] in d:\jw\ZumoSDKBuild_Dev\source\sdk\Managed\src\Microsoft.WindowsAzure.MobileServices\MobileServiceClient.cs:150
at Microsoft.WindowsAzure.MobileServices.MobileServiceClient..ctor (System.String applicationUrl, System.String applicationKey) [0x00000] in d:\jw\ZumoSDKBuild_Dev\source\sdk\Managed\src\Microsoft.WindowsAzure.MobileServices\MobileServiceClient.cs:135
at MyApp.App..ctor () [0x00009] in c:\Users\adam\Documents\Visual Studio 2013\Projects\MyApp\App.cs:30 }
Looking at the source code of the MobileServiceClient here is the function it is failing on
private string GetUserAgentHeader()
678 {
679 AssemblyFileVersionAttribute fileVersionAttribute = typeof(MobileServiceClient).GetTypeInfo().Assembly
680 .GetCustomAttributes(typeof(AssemblyFileVersionAttribute))
681 .Cast<AssemblyFileVersionAttribute>()
682 .FirstOrDefault();
683 string fileVersion = fileVersionAttribute.Version;
684 string sdkVersion = string.Join(".", fileVersion.Split('.').Take(2)); // Get just the major and minor versions
685
686 IPlatformInformation platformInformation = Platform.Instance.PlatformInformation;
687 return string.Format(
688 CultureInfo.InvariantCulture,
689 "ZUMO/{0} (lang={1}; os={2}; os_version={3}; arch={4}; version={5})",
690 sdkVersion,
691 "Managed",
692 platformInformation.OperatingSystemName,
693 platformInformation.OperatingSystemVersion,
694 platformInformation.OperatingSystemArchitecture,
695 fileVersion);
696 }
I have no idea on what is specifically causing the error. Any help appreciated.
Update
If I run the following code, just in my app before I try to initialize the MobileServiceClient
AssemblyFileVersionAttribute fileVersionAttribute = typeof(MobileServiceClient).GetTypeInfo().Assembly
.GetCustomAttributes(typeof(AssemblyFileVersionAttribute))
.Cast<AssemblyFileVersionAttribute>()
.FirstOrDefault();
string fileVersion = fileVersionAttribute.Version;
With Don't Link it works perfectly. If I run it with Link SDK or Link All then assembly is equal to null.
Where to go from here I am not sure yet.
The intent of linking is to reduce overall app size by excluding unused namespaces, classes, and members. Linking most apps will require a manual iterative process of:
Enable full linking for whatever build config you're concerned with.
Clean and build the app.
Run the app, and observe what runtime exceptions occur as a result of missing types and methods (including constructors).
Add rules either to your mtouch command arguments or the link description XML file in order to skip linking on the namespaces, types, and classes that you find are throwing exceptions.
In order to link an app that uses the Azure Mobile Services Client PCL, you follow the same iterative process I just stated.
I prefer the XML-based config file strategy of linking preservation:
https://developer.xamarin.com/guides/cross-platform/advanced/custom_linking/
The XML file is commonly known as a link definition file. It allows you to control the linker in a declarative fashion, without adding [Preserve] attributes everywhere in your code; and for third-party libraries, without muddying up the mtouch arguments of Xamarin.iOS projects or the csproj file of Xamarin.Android projects. It can be named whatever you want, as long as you properly tell your platform project about it.
An appropriate configuration could look like this:
<?xml version="1.0" encoding="UTF-8" ?>
<linker>
<assembly fullname="Microsoft.WindowsAzure.Mobile">
<type fullname="Microsoft*" />
</assembly>
<assembly fullname="Microsoft.WindowsAzure.Mobile.Ext">
<type fullname="Microsoft*" />
</assembly>
</linker>
In each assembly node, you describe the types or members you want to preserve. For the sake of simplicity here, I've used a wildcard to include all types that begin with "Microsoft". That's matched by fully qualified name, including namespace.
However, as stated, you will encounter a runtime problem with the GetUserAgentHeader() method in the MobileServiceHttpClient class:
Fortunately, the source code is available. So, I pulled down the source and referenced it in my project. The exception occurs on line 699, where the the Version property of the fileVersionAttribute var is attempted to be retrieved. But fileVersionAttribute is null!...when linked. The LINQ statement that begins on line 695 returns null when linking is enabled. It does return a valid value when not linked; a value of "1.0.0.0".
WHY? I'm not quite sure yet. But that's the root cause of the exception.
Anyway, for now I'll have to include the Azure Mobile Service source in my project, and artificially set that value to "1.0.0.0"...which is dirty, and I'm not happy about it.
string fileVersion = fileVersionAttribute?.Version ?? "1.0.0.0";
EDIT:
Issue raised on github: https://github.com/Azure/azure-mobile-services/issues/855
I have finally discovered a way to prevent the linking of the Azure Mobile Services library, without disabling linking for everything else.
You can add
--linkskip=Microsoft.WindowsAzure.Mobile --linkskip=Microsoft.WindowsAzure.Mobile.Ext
to Additional mtouch arguments in the iOS build options under project settings for the iOS project.
This will skip the linker for the azure assemblies, but not the rest. More on the linker can be found at http://developer.xamarin.com/guides/ios/advanced_topics/linker/#Skipping_Assemblies
I needed to add
CurrentPlatform.Init();
in the AppDelegate in FinishedLaunching
Secondly in the iOS project I needed to go to
Properties > iOS Build > Linker Behavior and set it to "Don't link"
I still don't consider this the answer, its just a poor work around at the moment.

How to inherit from DataAnnotations.ValidationAttribute (it appears SecureCritical under Visual Studio debugging host in .NET 4 !)

I have an [AllowPartiallyTrustedCallers] class library containing subtypes of the System.DataAnnotations.ValidationAttribute. The library is used on contract types of WCF services.
In .NET 2/3.5, this worked fine. Since .NET 4.0 however, running a client of the service in the Visual Studio debugger results in the exception "Inheritance security rules violated by type: '(my subtype of ValidationAttribute)'. Derived types must either match the security accessibility of the base type or be less accessible." (System.TypeLoadException)
The error appears to occure only when all of the following conditions are met:
a subclass of ValidationAttribute is in an AllowPartiallyTrustedCallers assembly
reflection is used to check for the attribute
the Visual Studio hosting process is enabled (checkbox on Project properties, Debug tab)
So basically, in Visual Studio.NET 2010:
create a new Console project,
add a reference to "System.ComponentModel.DataAnnotations" 4.0.0.0,
write the following code:
.
using System;
[assembly: System.Security.AllowPartiallyTrustedCallers()]
namespace TestingVaidationAttributeSecurity
{
public class MyValidationAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{ }
[MyValidation]
public class FooBar
{ }
class Program
{
static void Main(string[] args)
{
Console.WriteLine("ValidationAttribute IsCritical: {0}",
typeof(System.ComponentModel.DataAnnotations.ValidationAttribute).IsSecurityCritical);
FooBar fb = new FooBar();
fb.GetType().GetCustomAttributes(true);
Console.WriteLine("Press enter to end.");
Console.ReadLine();
}
}
}
Press F5 and you get the exception !
Press Ctrl-F5 (start without debugging), and it all works fine without exception...
The strange thing is that the ValidationAttribute will or will not be securitycritical depending on the way you run the program (F5 or Ctrl+F5). As illustrated by the Console.WriteLine in the above code. But then again, this appear to happen with other attributes (and types?) too.
Now the questions...
Why do I have this behaviour when inheriting from ValidationAttribute, but not when inheriting from System.Attribute ? (Using Reflector I don't find special settings on the ValidationAttribute class or it's assembly)
And what can I do to solve this ? How can I keep MyValidationAttribute inheriting from ValidationAttribute in an AllowPartiallyTrustedCallers assembly without marking it SecurityCritical, still using the new .NET 4 level 2 security model and still have it work using the VS.NET debug host (or other hosts) ??
Thanks a lot!
Rudi
Why do I have this behaviour when inheriting from ValidationAttribute, but not when inheriting from System.Attribute ? (Using Reflector I don't find special settings on the ValidationAttribute class or it's assembly)
This is because the System.ComponentModel.DataAnnotations assembly is conditionally APTCA i.e. it is marked with the following attribute.
[assembly: AllowPartiallyTrustedCallers(PartialTrustVisibilityLevel = PartialTrustVisibilityLevel.NotVisibleByDefault)]
Something about the way Visual Studio starts the host process causes the CLR not to respect APTCA on this assembly even though the default AppDomain is fully trusted. This implies that all the types and methods in the DataAnnotations assembly are SecurityCritical. Since a security transparent type (MyValidationAttribute) cannot inherit from a security critical type (ValidationAttribute), this exception is thrown.
And what can I do to solve this ? How can I keep MyValidationAttribute inheriting from ValidationAttribute in an AllowPartiallyTrustedCallers assembly without marking it SecurityCritical, still using the new .NET 4 level 2 security model and still have it work using the VS.NET debug host (or other hosts) ??
It seems like this is a bug with the VS host, which is unfortunate for your situation. On the other hand, you should really be sure that you want your assembly to be APTCA. If it's necessary, then you have a couple of options.
You can leave your assembly as is. This is advantageous because in the most typical partial trust environment, ASP.NET, the DataAnnotations assembly will always be considered APTCA. Of course, you lose the ability to use the debugger in the VS hosting process.
You can mark your assembly C-APTCA as well. You'll be able to use the debugger in the VS hosting process, but consumers of your assembly in ASP.NET will need to add your assembly to the <partialTrustVisibleAssemblies> element in the web.config in order for it to be APTCA.
You could make your attribute SecurityCritical, so you'll be able to use the debugger and will not require any special configuration in ASP.NET, but all classes that use your attribute must also be critical.
For some reason the site posted the text into a completely different question from the one that was on the page when I was writing - weird.

Subsonic 3.0 and SqlHierachyID

I am having trouble with Subsonic 3.0 generating an object for a table which contains the new HeirachyID datatype. From what I have found, there is no corrosponding .Net type, and subsonic doesn't seem to know how to handle the hierachyid data.
Error that is thrown:
Object of type 'Microsoft.SqlServer.Types.SqlHierarchyId' cannot be converted to type 'System.String'.
Code:
foreach (MyDB.DataAccess.ThingCategory tc in DataAccess.ThingCategory.Find(x => x.fk_Thing.Equals(thingId)))
{
sb.AppendFormat("<{0}>{1}</{0}>", wrapTag, tc.Categories.ToList<DataAccess.Category>()[0].Name);
}
tc.Categories.ToList() generates the error
Alternatively, I tried to get around this by writing a sproc to return the hierachyid column as a string, and noticed SubSonic 3.0 sprocs are not strongly-typed. or am I doing something wrong?
Sprocs can be strongly-typed by calling ExecuteTypedList()
I would create an issue on the Github tracker to either add support for the type (someone will have to contribute this since I don't think it's a high priority) or to gracefully handle it when they exist.

Weird Silverlight Designer Error

I get the following exception loading any Xaml in my project:
'/Microsoft.VisualStudio.Xaml;Component/MS/Internal/Designer/PropertyEditing/Resources/StylesCore.Constants.xaml' value cannot be assigned to property 'Source' of object 'System.Windows.ResourceDictionary'. Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821' or one of its dependencies. The system cannot find the file specified. Error at object 'ResourceDictionary_2' in markup file 'Microsoft.VisualStudio.Xaml;component/MS/Internal/Designer/PropertyEditing/Resources/StylesCore.xaml'.
at System.Windows.Markup.XamlParseException.ThrowException(String message, Exception innerException, Int32 lineNumber, Int32 linePosition, Uri baseUri, XamlObjectIds currentXamlObjectIds, XamlObjectIds contextXamlObjectIds, Type objectType)
at System.Windows.Markup.XamlParseException.ThrowException(ParserContext parserContext, Int32 lineNumber, Int32 linePosition, String message, Exception innerException)
at System.Windows.Markup.BamlRecordReader.ThrowExceptionWithLine(String message, Exception innerException)
at System.Windows.Markup.BamlRecordReader.ReadPropertyRecordBase(String attribValue, Int16 attributeId, Int16 converterTypeId)
at System.Windows.Markup.BamlRecordReader.ReadPropertyConverterRecord(BamlPropertyWithConverterRecord bamlPropertyRecord)
at System.Windows.Markup.BamlRecordReader.ReadRecord(BamlRecord bamlRecord)
at System.Windows.Markup.BamlRecordReader.Read(Boolean singleRecord)
at System.Windows.Markup.TreeBuilderBamlTranslator.ParseFragment()
at System.Windows.Markup.TreeBuilder.Parse()
at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
at System.Windows.Application.LoadBamlStreamWithSyncInfo(Stream stream, ParserContext pc)
at System.Windows.Application.LoadComponent(Uri resourceLocator, Boolean bSkipJournaledProperties)
at System.Windows.Application.LoadComponent(Uri resourceLocator)
at MS.Internal.Designer.PropertyEditing.Resources.PropertyInspectorResources.GetResources()
at MS.Internal.Designer.PropertyEditing.PropertyInspectorHost.get_Host()
at MS.Internal.Designer.VSDesigner.VSDesignerClientImpl.get_PropertyWindow()
at MS.Internal.Designer.VSDesignerClient.get_PropertyWindow()
at MS.Internal.Designer.DesignerPane.LoadDesignerView()
This occurs even when I generate a new SilverLight project inside my solution, but not in a brand new solution. I've found that I am not the only person with this issue, and was wondering if you had any ideas for me.
Here is a post of someone with the same error, from Google Cache.
The stack trace is indicating you don't have a reference to the specified log4net assembly in your project. The solution would be to add a reference to it, although unless you get a log4net assembly that has been compiled against the Silverlight agCLR runtime you won't be able to.
The alternative if you are not trying to use log4net in your Silverlight app is to remove the sections of code attempting to use it. Again from the stack trace it looks like you are setting up some kind of resource that initialises log4net. Try opening your Windox.xaml and take a look in the reources section. If you see any signs of log4net there remove them and see if it helps.
I also am getting this error. I have gone through the application and made sure I am referencing the correct version. There is no use of log4net in the silverlight application, only in the web project containing a wcf service that the app uses. It looks like log4net has to be replaced with something safer. The log4net dll is also causing mstest projects to stop working.
'/Microsoft.VisualStudio.Xaml;Component/MS/Internal/Designer/PropertyEditing/Resources/StylesCore.Constants.xaml' value cannot be assigned to property 'Source' of object 'System.Windows.ResourceDictionary'. Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821' or one of its dependencies. The system cannot find the file specified. Error at object 'ResourceDictionary_2' in markup file 'Microsoft.VisualStudio.Xaml;component/MS/Internal/Designer/PropertyEditing/Resources/StylesCore.xaml'.
I have no idea what the couse of the problem is. If anyone knows I would be interested find out!
I have a workaround though which solved it for me:
Remove the reference from the Silverlight project to whatever is using log4net
Remove that project using log4net from the solution.
Reload the XAML-pages and save the solution.
Finally add the project using log4net and the reference again.
Henrik

Resources