Error after upgrading to Azure Mobile Services 1.3.1 - xamarin.ios

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.

Related

An item with the same key has already been added error in 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.

"mscorlib.pdb not loaded" yet the mscorlib.dll is NOT missing

I am running my application in VS2012 and I am getting a runtime error;
When I look in the "Original Location" I see mscorlib.dll, but not mscorlib.pdb.
Why is this happening and how do I fix it?
Goto Tools, Options, Debugging, General, Enable Just My Code
This will prevent the debugger from trying to launch on a Internal .NET Framework Assembly.
Goto Tools, Options, Debugging, Symbols and set a cache location. Then hit load in the above and it will fetch the necesary symbols for you and store them in the cache location you provide.
Microsoft's compiler tools create symbols in separate files with a .pdb extension (program database). This allows them to create detached symbols for release binaries. With a symbol server, your IDE can fetch the symbol file matching the specific version of the DLL during debugging. You can configure this system for your own product binaries as well which can be very useful for post-mortem debugging any crashes on end-user machines.
See Microsoft's documentation for more details about using their public symbols.
I had this issue when I was using a static variable, whose value is assigned off a static method.
So, whenever I ran the application, this line of code threw exception. If you place a debug point on this (like I did), you will notice the exception being thrown.
The best Solution to solve this error is:
1: Open App.config file.
2: Paste this useLegacyV2RuntimeActivationPolicy="true" code in the startup tag.
3: Save it.
Now the error would disappear.
Moreover see Image. I have done this for you.
This happened to me for a different reason: I had referenced an old version of NLog (2.0) and needed to reference version 4.0, instead.
In a VB console app, in my case it was none of the above.
Just doing a string calculation in the Dim declarations before my subs.
The offending code:
Dim FylPrefix$ = Fyl.Substring(0, Fyl.LastIndexOf("."))
Moving this calculation into the sub it was needed in fixed it! GERONIMO!!
This can happen when you initialize a variable in your class declarations and that initialization throws an exception:
class Program
{
static OracleConnection ora = getOracleConnection();
}
static void main(string[] args)
{
ora.Open();
}
static OracleConnection getOracleConnection()
{
OracleConnection orax = new OracleConnection(description=(host=myHost)
(port=1521)(protocol=tcp))(connect_data=(sid=mySid)));user id=user;password=pw;
}
If an exception is thrown by getOracleConnection() you can get this error. Move your assignment (but not necessarily your declaration) inside of main (where it belongs anyway), and you will get the actual exception that is causing the error instead of the mscorlib error.
In my case the exception began to appear after I changed the "Assembly name" in the "Application" tab of the properties window. If that's the case with you try reverting to the original name and see if the exception disappears.
Perhaps the reason for this was that the new name did not match the AssemblyTitle in AssemblyInfo.cs.
if you have this type of project runtime error in visualstudio
Answer:Cntr+Alt+E open Exception window Uncheck All chechboxes
Must and shoud its working written by B sriram Mca Giet College
rajahmundry, east godavary ,2014 batch

Attempt to initialize the CRT more than once

I am using VS2008 to port code from VC6. When I ran the new build app, I get this error "R6031 Attemp to initialize the CRT more than once. This indicates a bug in your application".
There are a total of 21 dlls that are involve in the build this one app. Some DLL has .c files in them and explicitly calls _CRT_INIT() in DllMain. code below:
BOOL APIENTRY DllMain (HANDLE hModule, DWORD dwReason, LPVOID lpReserved)
{
switch( dwReason)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
if(!_CRT_INIT( hModule, dwReason, lpReserved))
return FALSE;
break;
}
return TRUE;
}
I am not sure how to fix this problem. Do I need to comment out the call to _CRT_INIT()?
Thanks in advance.
Yes, you should not need to call _CRT_INIT() explicitly. It's probably being called by one or another DLLMain.
See MSDN for details.
Edit
I think you have misread MSDN:
When building a DLL which uses any of
the C Run-time libraries, in order to
ensure that the CRT is properly
initialized, either
the initialization function must be named DllMain() and the entry point
must be specified with the linker
option -entry:_DllMainCRTStartup#12 -
or -
You have named the init function DllMain(), so _CRT_INIT() is being called automatically. I think.
Why not simply comment out that line and see what happens?
This error code is specific to mixed-mode assemblies. Have you enabled the CLR during the port by mistake? You should not see this during a simple port from VC6 to a later Visual C++ revision.
This diagnostic indicates that MSIL
instructions were executing during
loader lock. For more information, see
Initialization of Mixed Assemblies.
You can check the project setting by right-clicking the project in Solution Explorer, then under Properties look at Configuration Properties -> General -> Common Language Runtime Support

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.

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