CORS with WebAPI sometimes works, sometimes doesn't - asp.net-web-api
I've used the following:
http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
As suggested here:
Enabling CORS with WebAPI PUT / POST requests?
to enable cross-origin AJAX requests in my project. Everything (POST / PUT / DELETE / GET) was working yesterday. Then I decided to add a new endpoint to my webAPI project, and this one is failing with:
> XMLHttpRequest cannot load http://localhost:24144/api/card. Origin
> http://localhost:11089 is not allowed by Access-Control-Allow-Origin.
In my WebApiConfig I've done this:
var cors = new EnableCorsAttribute("http://localhost:11089", "*", "*");
config.EnableCors(cors);
And my AJAX request, identical to others that are working, looks like this:
var updateCard = function (data) {
var options = {
url: apiEndpoint + 'card',
type: 'PUT',
async: true,
dataType: 'json',
data: data,
xhrFields: {
withCredentials: true
}
};
return $.ajax(options)
.done(function (response) {
toastr.success("Card Updated", "Success");
})
.fail(function (msg) {
toastr.error("Could not update card.", "Error");
});
}
};
Even if use the attribute directly on the method or controller that's failing, I get the same error:
[EnableCors(origins: "http://localhost:11089", headers: "*", methods: "*")]
Why would this be happening? I noticed that if I kill my webAPI solution while debugging, I get the same error in the client, but it usually only happens once and expected behavior resumes with the WebAPI project. This isn't a problem but maybe it's relevant.
If there's anything else you think I should provide here, let me know.
Update: Stack:
iisexpress.exe Information: 0 : Request, Method=OPTIONS, Url=http://localhost:24144/api/card, Message='http://localhost:24144/api/card'
iisexpress.exe Information: 0 : Message='Card', Operation=DefaultHttpControllerSelector.SelectController
iisexpress.exe Information: 0 : Message='Selected action 'UpdateCard(CardDto card)'', Operation=ApiControllerActionSelector.SelectAction
iisexpress.exe Information: 0 : Message='CorsPolicyProvider selected: 'System.Web.Http.Cors.EnableCorsAttribute'', Operation=AttributeBasedPolicyProviderFactory.GetCorsPolicyProvider
iisexpress.exe Information: 0 : Message='CorsPolicy selected: 'AllowAnyHeader: True, AllowAnyMethod: True, AllowAnyOrigin: False, PreflightMaxAge: null, SupportsCredentials: False, Origins: {http://localhost:11089}, Methods: {}, Headers: {}, ExposedHeaders: {}'', Operation=EnableCorsAttribute.GetCorsPolicyAsync
iisexpress.exe Information: 0 : Message='CorsResult returned: 'IsValid: True, AllowCredentials: False, PreflightMaxAge: null, AllowOrigin: http://localhost:11089, AllowExposedHeaders: {}, AllowHeaders: {accept,origin,content-type}, AllowMethods: {PUT}, ErrorMessages: {}'', Operation=CorsEngine.EvaluatePolicy
iisexpress.exe Information: 0 : Operation=CorsMessageHandler.SendAsync, Status=200 (OK)
iisexpress.exe Information: 0 : Response, Status=200 (OK), Method=OPTIONS, Url=http://localhost:24144/api/card, Message='Content-type='none', content-length=unknown'
iisexpress.exe Information: 0 : Request, Method=PUT, Url=http://localhost:24144/api/card, Message='http://localhost:24144/api/card'
iisexpress.exe Information: 0 : Message='Card', Operation=DefaultHttpControllerSelector.SelectController
iisexpress.exe Information: 0 : Message='App.Service.Controllers.CardController', Operation=DefaultHttpControllerActivator.Create
iisexpress.exe Information: 0 : Message='App.Service.Controllers.CardController', Operation=HttpControllerDescriptor.CreateController
iisexpress.exe Information: 0 : Message='Selected action 'UpdateCard(CardDto card)'', Operation=ApiControllerActionSelector.SelectAction
iisexpress.exe Information: 0 : Operation=AuthorizeAttribute.OnAuthorization
iisexpress.exe Information: 0 : Message='Value read='App.Repository.Models.Dtos.CardDto'', Operation=JQueryMvcFormUrlEncodedFormatter.ReadFromStreamAsync
iisexpress.exe Information: 0 : Message='Parameter 'card' bound to the value 'App.Repository.Models.Dtos.CardDto'', Operation=FormatterParameterBinding.ExecuteBindingAsync
iisexpress.exe Information: 0 : Message='Model state is valid. Values: card=App.Repository.Models.Dtos.CardDto', Operation=HttpActionBinding.ExecuteBindingAsync
A first chance exception of type 'System.Data.Entity.Validation.DbEntityValidationException' occurred in EntityFramework.dll
iisexpress.exe Information: 0 : Message='Will use same 'JsonMediaTypeFormatter' formatter', Operation=JsonMediaTypeFormatter.GetPerRequestFormatterInstance
iisexpress.exe Information: 0 : Message='Selected formatter='JsonMediaTypeFormatter', content-type='application/json; charset=utf-8'', Operation=DefaultContentNegotiator.Negotiate
iisexpress.exe Information: 0 : Message='Action returned 'StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.ObjectContent`1[[System.Exception, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], Headers:
{
Content-Type: application/json; charset=utf-8
}'', Operation=ReflectedHttpActionDescriptor.ExecuteAsync
iisexpress.exe Information: 0 : Operation=ApiControllerActionInvoker.InvokeActionAsync, Status=500 (InternalServerError)
iisexpress.exe Information: 0 : Operation=CardController.ExecuteAsync, Status=500 (InternalServerError)
iisexpress.exe Information: 0 : Message='CorsPolicyProvider selected: 'System.Web.Http.Cors.EnableCorsAttribute'', Operation=AttributeBasedPolicyProviderFactory.GetCorsPolicyProvider
iisexpress.exe Information: 0 : Message='CorsPolicy selected: 'AllowAnyHeader: True, AllowAnyMethod: True, AllowAnyOrigin: False, PreflightMaxAge: null, SupportsCredentials: False, Origins: {http://localhost:11089}, Methods: {}, Headers: {}, ExposedHeaders: {}'', Operation=EnableCorsAttribute.GetCorsPolicyAsync
iisexpress.exe Information: 0 : Message='CorsResult returned: 'IsValid: True, AllowCredentials: False, PreflightMaxAge: null, AllowOrigin: http://localhost:11089, AllowExposedHeaders: {}, AllowHeaders: {}, AllowMethods: {}, ErrorMessages: {}'', Operation=CorsEngine.EvaluatePolicy
iisexpress.exe Information: 0 : Operation=CorsMessageHandler.SendAsync, Status=500 (InternalServerError)
iisexpress.exe Information: 0 : Response, Status=500 (InternalServerError), Method=PUT, Url=http://localhost:24144/api/card, Message='Content-type='application/json; charset=utf-8', content-length=unknown'
iisexpress.exe Error: 0 : Operation=JsonMediaTypeFormatter.WriteToStreamAsync, Exception=Newtonsoft.Json.JsonSerializationException: Error getting value from 'Stage' on 'System.Data.Entity.DynamicProxies.Side_F7B85DBC8AA69F5AAA5ACCA92A66F2763E57D4D2046F02AC7EE6064A3409DE42'. ---> System.ObjectDisposedException: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
at System.Data.Objects.ObjectContext.EnsureConnection()
at System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
at System.Data.Objects.ObjectQuery`1.Execute(MergeOption mergeOption)
at System.Data.Objects.DataClasses.EntityReference`1.Load(MergeOption mergeOption)
at System.Data.Objects.DataClasses.RelatedEnd.Load()
at System.Data.Objects.DataClasses.RelatedEnd.DeferredLoad()
at System.Data.Objects.Internal.LazyLoadBehavior.LoadProperty[TItem](TItem propertyValue, String relationshipName, String targetRoleName, Boolean mustBeNull, Object wrapperObject)
at System.Data.Objects.Internal.LazyLoadBehavior.<>c__DisplayClass7`2.<GetInterceptorDelegate>b__2(TProxy proxy, TItem item)
at System.Data.Entity.DynamicProxies.Side_F7B85DBC8AA69F5AAA5ACCA92A66F2763E57D4D2046F02AC7EE6064A3409DE42.get_Stage()
at GetStage(Object )
at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)
--- End of inner exception stack trace ---
at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract& memberContract, Object& memberValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value)
at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value)
at Newtonsoft.Json.JsonSerializer.Serialize(JsonWriter jsonWriter, Object value)
at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)
at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at System.Web.Http.Tracing.ITraceWriterExtensions.<TraceBeginEndAsyncCore>d__33.MoveNext()
iisexpress.exe Information: 0 : Message='Will use same 'JsonMediaTypeFormatter' formatter', Operation=JsonMediaTypeFormatter.GetPerRequestFormatterInstance
iisexpress.exe Information: 0 : Message='Selected formatter='JsonMediaTypeFormatter', content-type='application/json; charset=utf-8'', Operation=DefaultContentNegotiator.Negotiate
iisexpress.exe Information: 0 : Operation=JsonMediaTypeFormatter.WriteToStreamAsync
iisexpress.exe Information: 0 : Operation=CardController.Dispose
In case anyone else runs into this and happens to be using Unit Of Work and CORS from WebAPI2 with EF (ha) -
I had a lazily-loaded property that was not available when the Update method was executing. I don't know why the error thrown was inaccurate, but the stack trace pointed me in the right direction:
Error getting value from 'Stage' on
'System.Data.Entity.DynamicProxies.Side_F7B85DBC8AA69F5AAA5ACCA92A66F2763E57D4D2046F02AC7EE6064A3409DE42'.
---> System.ObjectDisposedException: The ObjectContext instance has been disposed and can no longer be used for operations that require a
connection.
If you are using IIS 7.5 or below use this config
<system.webServer>
<handlers>
<remove name="OPTIONSVerbHandler"/>
</handlers>
</system.webServer>
Or if you are using IIS 8 or above
<system.webServer>
<handlers>
<remove name="OPTIONS"/>
</handlers>
</system.webServer>
Hope this help
Related
Uninstalling Visual Studio 2017 "Unexpected character encountered while parsing value"
I'm attempting to uninstall Visual Studio Enterprise 2017 using the Visual Studio Installer on Windows 10 Professional but when I try to do so I hit this error: [0d1c:002d][2020-02-12T16:28:26] Error 0x80131500: Unexpected character encountered while parsing value: <. Path ''. at Newtonsoft.Json.JsonTextReader.ParseValue() at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent) at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType) at Newtonsoft.Json.JsonSerializer.Deserialize[T](JsonReader reader) at Microsoft.VisualStudio.Setup.Serialization.ModelSerializer`1.Deserialize(TextReader reader) at Microsoft.VisualStudio.Setup.Cache.DirectoryRepository.GetPackage(IPackageIdentity identity) at Microsoft.VisualStudio.Setup.Cache.CacheRepository.GetPackage(IPackageIdentity identity) at Microsoft.VisualStudio.Setup.Installer.Extensions.IsPayloadRequired(IInstallablePackage package, ExecuteAction action, IServiceProvider services, ExecuteAction bootstrapperAction) at Microsoft.VisualStudio.Setup.InstallOperation.CreateDownloadInstallActivities(InstallablePackage installable, ExecuteAction action, Boolean isPresent) at Microsoft.VisualStudio.Setup.InstallOperation.PlanInstallable(InstallablePackage installable, Dictionary`2 downloadLookup, PackagePlan& packagePlan, Boolean repairPackagesWithDuplicateFiles, Boolean upgradeConfigurationPackage) at Microsoft.VisualStudio.Setup.InstallOperation.Plan() at Microsoft.VisualStudio.Setup.InstallOperation.Schedule() at Microsoft.VisualStudio.Setup.Engine.CreateInstallOperation(Product product, String destination, ExecuteAction action, ITelemetryOperation telemetryOperation) at Microsoft.VisualStudio.Setup.Engine.Uninstall(CancellationToken token) Has anyone else run into this issue and know how to successfully uninstall this application?
This same happened to me. Can not repair or update. Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: . Path '', line 1, position 146. at Microsoft.VisualStudio.Setup.Engine.Initialize() at Microsoft.VisualStudio.Setup.Engine.GetProducts() at Microsoft.VisualStudio.ExtensionManager.ExtensionEngineImpl.IntializePackages() at Microsoft.VisualStudio.ExtensionManager.ExtensionEngineImpl.GetPrerequisitesInternal(IInstallableExtension extension, ICollection`1 installedPackages, ICollection`1 installablePackages, ICollection`1 unresolvedReferences) at Microsoft.VisualStudio.ExtensionManager.ExtensionEngineImpl.GetPrerequisites(IInstallableExtension extension, IEnumerable`1& installedPackages, IEnumerable`1& installablePackages, IEnumerable`1& unresolvedReferences) at VSIXInstaller.ExtensionService.GetInstallableData(String vsixPath, String extensionPackParentName, Boolean isRepairSupported, IStateData stateData, IEnumerable`1& skuData) at VSIXInstaller.App.Initialize(Boolean isRepairSupported) at VSIXInstaller.App.Initialize() at System.Threading.Tasks.Task`1.InnerInvoke() at System.Threading.Tasks.Task.Execute() --- End of stack trace from previous location where exception was thrown --- at Microsoft.VisualStudio.Telemetry.WindowsErrorReporting.WatsonReport.GetClrWatsonExceptionInfo(Exception exceptionObject) To uninstall use: https://learn.microsoft.com/en-us/visualstudio/install/remove-visual-studio?view=vs-2019
JsonResult Response from WebAPI for Elasticsearch NEST query
I have created WEBAPI methods, to search ES using NEST. The search with ES is working as expected. The issue that I have is when I try to return the Json(response) using POSTMAN, it throws this exception: { "Message": "An error has occurred.", "ExceptionMessage": "If you use a custom contract resolver be sure to subclass from ElasticContractResolver", "ExceptionType": "System.Exception", "StackTrace": " at Nest.JsonExtensions.GetConnectionSettings(JsonSerializer serializer)\r\n at Nest.VerbatimDictionaryKeysJsonConverter2.WriteJson(JsonWriter writer, Object value, JsonSerializer serializer)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeConvertable(JsonWriter writer, JsonConverter converter, Object value, JsonContract contract, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)\r\n at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)\r\n at System.Web.Http.Results.JsonResult1.Serialize()\r\n at System.Web.Http.Results.JsonResult1.Execute()\r\n at System.Web.Http.Results.JsonResult1.ExecuteAsync(CancellationToken cancellationToken)\r\n at System.Web.Http.Controllers.ApiControllerActionInvoker.d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ActionFilterResult.d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.AuthenticationFilterResult.d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()" } This is my WEB API method [System.Web.Http.Route("SearchElastic")] [System.Web.Http.HttpPost] public JsonResult<ISearchResponse<T>> SearchElastic([FromBody] ElasticSearchRequest esRequest) { var searchResponse = EsClient.Search<T>( "...NEST query..." )); return Json(searchResponse); } //<T> is a custom C# class. I am using Elasticsearch/NEST 5.x.
The error message hints at what the problem is { "Message": "An error has occurred.", "ExceptionMessage": "If you use a custom contract resolver be sure to subclass from ElasticContractResolver", "ExceptionType": "System.Exception", "StackTrace": " at ... and it relates to the line return Json(searchResponse); the configuration for the Json serializer used by Web API does not know how to handle serializing certain types from NEST because some of those types need ElasticContractResolver to be serialized correctly. There are a few ways to solve this, but the two most straightforward are: Configure the Json Serializer used by Web API with ElasticContractResolver as the IContractResolver on the JsonSerializerSettings. The disadvantage here is that all of your types that you're serializing to json will be going through NEST's resolver Avoid the deserialization/re-serialization loop from Elasticsearch -> deserialized by NEST -> reserialized by Web API altogether by using the low level client to return a string or byte array from Elasticsearch. I would recommend this approach if you are not doing any introspection on searchResponse. If you do need to inspect searchResponse, you can always deserialize the string or byte array to SearchResponse<T> as a separate step. This is one of the reasons that the direct dependency on Json.NET has been removed in NEST 6.x
Visual Studio - can't build anything
I worked arround with visual studio and cordova every thing was fine but suddenly when i want to build the app for iOS (doesn't matter if ripple or remote device) after a abouut two seconds I get the following error message. It really appeared from one to another second... I did nothing special. Also when i create a blank project it doesn't work - same issue! Error - Cannot load global packages. System.AggregateException: Mindestens ein Fehler ist aufgetreten. ---> Microsoft.NodejsTools.Npm.PackageJsonException: Error reading package.json at 'C:\Users\m.hüttl\AppData\Roaming\npm\node_modules\phonegap\node_modules\cordova\node_modules\cordova-lib\node_modules\npm\node_modules\graceful-fs\package.json': Error reading package.json. The file may be parseable JSON but may contain objects with duplicate properties. The following error occurred: Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject. ---> Microsoft.NodejsTools.Npm.PackageJsonException: Error reading package.json. The file may be parseable JSON but may contain objects with duplicate properties. The following error occurred: Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject. ---> System.ArgumentException: Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject. bei Newtonsoft.Json.Linq.JObject.ValidateToken(JToken o, JToken existing) bei Newtonsoft.Json.Linq.JContainer.InsertItem(Int32 index, JToken item, Boolean skipParentCheck) bei Newtonsoft.Json.Linq.JObject.InsertItem(Int32 index, JToken item, Boolean skipParentCheck) bei Newtonsoft.Json.Linq.JContainer.AddInternal(Int32 index, Object content, Boolean skipParentCheck) bei Newtonsoft.Json.Linq.JContainer.Add(Object content) bei Newtonsoft.Json.Linq.JTokenWriter.AddValue(JValue value, JsonToken token) bei Newtonsoft.Json.Linq.JTokenWriter.WriteNull() bei Newtonsoft.Json.JsonWriter.AutoCompleteClose(JsonContainerType type) bei Newtonsoft.Json.JsonWriter.WriteEndObject() bei Newtonsoft.Json.JsonWriter.WriteEnd(JsonContainerType type) bei Newtonsoft.Json.JsonWriter.WriteEnd() bei Newtonsoft.Json.JsonWriter.AutoCompleteAll() bei Newtonsoft.Json.Linq.JTokenWriter.Close() bei Newtonsoft.Json.JsonWriter.System.IDisposable.Dispose() bei Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateJObject(JsonReader reader) bei Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue) bei Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue) bei Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent) bei Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType) bei Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings) bei Microsoft.NodejsTools.Npm.ReaderPackageJsonSource..ctor(TextReader reader) --- Ende der internen Ausnahmestapelüberwachung --- bei Microsoft.NodejsTools.Npm.ReaderPackageJsonSource..ctor(TextReader reader) bei Microsoft.NodejsTools.Npm.FilePackageJsonSource..ctor(String fullPathToFile) --- Ende der internen Ausnahmestapelüberwachung --- bei Microsoft.NodejsTools.Npm.FilePackageJsonSource.WrapExceptionAndRethrow(String fullPathToFile, Exception ex) bei Microsoft.NodejsTools.Npm.FilePackageJsonSource..ctor(String fullPathToFile) bei Microsoft.NodejsTools.Npm.DirectoryPackageJsonSource..ctor(String fullDirectoryPath) bei Microsoft.NodejsTools.Npm.SPI.RootPackage..ctor(String fullPathToRootDirectory, Boolean showMissingDevOptionalSubPackages) bei Microsoft.NodejsTools.Npm.SPI.NodeModules..ctor(IRootPackage parent, Boolean showMissingDevOptionalSubPackages) bei Microsoft.NodejsTools.Npm.SPI.RootPackage..ctor(String fullPathToRootDirectory, Boolean showMissingDevOptionalSubPackages) bei Microsoft.NodejsTools.Npm.SPI.NodeModules..ctor(IRootPackage parent, Boolean showMissingDevOptionalSubPackages) bei Microsoft.NodejsTools.Npm.SPI.RootPackage..ctor(String fullPathToRootDirectory, Boolean showMissingDevOptionalSubPackages) bei Microsoft.NodejsTools.Npm.SPI.NodeModules..ctor(IRootPackage parent, Boolean showMissingDevOptionalSubPackages) bei Microsoft.NodejsTools.Npm.SPI.RootPackage..ctor(String fullPathToRootDirectory, Boolean showMissingDevOptionalSubPackages) bei Microsoft.NodejsTools.Npm.SPI.NodeModules..ctor(IRootPackage parent, Boolean showMissingDevOptionalSubPackages) bei Microsoft.NodejsTools.Npm.SPI.RootPackage..ctor(String fullPathToRootDirectory, Boolean showMissingDevOptionalSubPackages) bei Microsoft.NodejsTools.Npm.SPI.NodeModules..ctor(IRootPackage parent, Boolean showMissingDevOptionalSubPackages) bei Microsoft.NodejsTools.Npm.SPI.RootPackage..ctor(String fullPathToRootDirectory, Boolean showMissingDevOptionalSubPackages) bei Microsoft.NodejsTools.Npm.SPI.NpmController.d__1.MoveNext() --- Ende der internen Ausnahmestapelüberwachung --- ---> (Interne Ausnahme #0) Microsoft.NodejsTools.Npm.PackageJsonException: Error reading package.json at 'C:\Users\m.hüttl\AppData\Roaming\npm\node_modules\phonegap\node_modules\cordova\node_modules\cordova-lib\node_modules\npm\node_modules\graceful-fs\package.json': Error reading package.json. The file may be parseable JSON but may contain objects with duplicate properties. The following error occurred: Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject. ---> Microsoft.NodejsTools.Npm.PackageJsonException: Error reading package.json. The file may be parseable JSON but may contain objects with duplicate properties. The following error occurred: Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject. ---> System.ArgumentException: Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject. bei Newtonsoft.Json.Linq.JObject.ValidateToken(JToken o, JToken existing) bei Newtonsoft.Json.Linq.JContainer.InsertItem(Int32 index, JToken item, Boolean skipParentCheck) bei Newtonsoft.Json.Linq.JObject.InsertItem(Int32 index, JToken item, Boolean skipParentCheck) bei Newtonsoft.Json.Linq.JContainer.AddInternal(Int32 index, Object content, Boolean skipParentCheck) bei Newtonsoft.Json.Linq.JContainer.Add(Object content) bei Newtonsoft.Json.Linq.JTokenWriter.AddValue(JValue value, JsonToken token) bei Newtonsoft.Json.Linq.JTokenWriter.WriteNull() bei Newtonsoft.Json.JsonWriter.AutoCompleteClose(JsonContainerType type) bei Newtonsoft.Json.JsonWriter.WriteEndObject() bei Newtonsoft.Json.JsonWriter.WriteEnd(JsonContainerType type) bei Newtonsoft.Json.JsonWriter.WriteEnd() bei Newtonsoft.Json.JsonWriter.AutoCompleteAll() bei Newtonsoft.Json.Linq.JTokenWriter.Close() bei Newtonsoft.Json.JsonWriter.System.IDisposable.Dispose() bei Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateJObject(JsonReader reader) bei Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue) bei Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue) bei Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent) bei Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType) bei Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings) bei Microsoft.NodejsTools.Npm.ReaderPackageJsonSource..ctor(TextReader reader) --- Ende der internen Ausnahmestapelüberwachung --- bei Microsoft.NodejsTools.Npm.ReaderPackageJsonSource..ctor(TextReader reader) bei Microsoft.NodejsTools.Npm.FilePackageJsonSource..ctor(String fullPathToFile) --- Ende der internen Ausnahmestapelüberwachung --- bei Microsoft.NodejsTools.Npm.FilePackageJsonSource.WrapExceptionAndRethrow(String fullPathToFile, Exception ex) bei Microsoft.NodejsTools.Npm.FilePackageJsonSource..ctor(String fullPathToFile) bei Microsoft.NodejsTools.Npm.DirectoryPackageJsonSource..ctor(String fullDirectoryPath) bei Microsoft.NodejsTools.Npm.SPI.RootPackage..ctor(String fullPathToRootDirectory, Boolean showMissingDevOptionalSubPackages) bei Microsoft.NodejsTools.Npm.SPI.NodeModules..ctor(IRootPackage parent, Boolean showMissingDevOptionalSubPackages) bei Microsoft.NodejsTools.Npm.SPI.RootPackage..ctor(String fullPathToRootDirectory, Boolean showMissingDevOptionalSubPackages) bei Microsoft.NodejsTools.Npm.SPI.NodeModules..ctor(IRootPackage parent, Boolean showMissingDevOptionalSubPackages) bei Microsoft.NodejsTools.Npm.SPI.RootPackage..ctor(String fullPathToRootDirectory, Boolean showMissingDevOptionalSubPackages) bei Microsoft.NodejsTools.Npm.SPI.NodeModules..ctor(IRootPackage parent, Boolean showMissingDevOptionalSubPackages) bei Microsoft.NodejsTools.Npm.SPI.RootPackage..ctor(String fullPathToRootDirectory, Boolean showMissingDevOptionalSubPackages) bei Microsoft.NodejsTools.Npm.SPI.NodeModules..ctor(IRootPackage parent, Boolean showMissingDevOptionalSubPackages) bei Microsoft.NodejsTools.Npm.SPI.RootPackage..ctor(String fullPathToRootDirectory, Boolean showMissingDevOptionalSubPackages) bei Microsoft.NodejsTools.Npm.SPI.NodeModules..ctor(IRootPackage parent, Boolean showMissingDevOptionalSubPackages) bei Microsoft.NodejsTools.Npm.SPI.RootPackage..ctor(String fullPathToRootDirectory, Boolean showMissingDevOptionalSubPackages) bei Microsoft.NodejsTools.Npm.SPI.NpmController.d__1.MoveNext()<---
Newtonsoft.Json on Xamarin - Unexpected Member Type
I've started seeing a strange exception when I recently upgraded the Newtonsoft.Json package in my Xamarin Forms project to v8.0.1. I'm seeing the same issue in three different projects when I try to deserialize objects. It doesn't happen with every single call to deserialize but it happens consistently with specific calls. These are all projects where the code hasn't changed and I don't believe the JSON has changed so this looks to me like an issue with either Newtonsoft or Xamarin? Is anyone else seeing this issue? Exception Details: Source: Newtonsoft.Json Message: Unexpected member type. StackTrace: Newtonsoft.Json.Utilities.TypeExtensions.TestAccessibility (System.Reflection.MemberInfo member, BindingFlags bindingFlags) [0x0003f] in :0 at Newtonsoft.Json.Utilities.TypeExtensions+<>c__DisplayClass34_0.b__0 (System.Reflection.MemberInfo m) [0x00013] in :0 at System.Linq.Enumerable+WhereListIterator1[TSource].MoveNext () [0x00048] in /Users/builder/data/lanes/2377/73229919/source/maccore/_build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/external/referencesource/System.Core/System/Linq/Enumerable.cs:232 at System.Linq.Buffer1[TElement]..ctor (IEnumerable1 source) [0x00083] in /Users/builder/data/lanes/2377/73229919/source/maccore/_build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/external/referencesource/System.Core/System/Linq/Enumerable.cs:2570 at System.Linq.Enumerable.ToArray[TSource] (IEnumerable1 source) [0x00011] in /Users/builder/data/lanes/2377/73229919/source/maccore/_build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/external/referencesource/System.Core/System/Linq/Enumerable.cs:830 at Newtonsoft.Json.Utilities.TypeExtensions.GetMember (System.Type type, System.String member, BindingFlags bindingFlags) [0x00030] in :0 at Newtonsoft.Json.Utilities.TypeExtensions.GetMember (System.Type type, System.String name, MemberTypes memberType, BindingFlags bindingFlags) [0x0000d] in :0 at Newtonsoft.Json.Utilities.ReflectionUtils.GetMemberInfoFromType (System.Type targetType, System.Reflection.MemberInfo memberInfo) [0x00066] in :0 at Newtonsoft.Json.Serialization.JsonTypeReflector.GetAttribute[T] (System.Reflection.MemberInfo memberInfo) [0x0005f] in :0 at Newtonsoft.Json.Serialization.JsonTypeReflector.GetAttribute[T] (System.Object provider) [0x0001b] in :0 at Newtonsoft.Json.Serialization.DefaultContractResolver.GetSerializableMembers (System.Type objectType) [0x000cf] in :0 at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateProperties (System.Type type, MemberSerialization memberSerialization) [0x00000] in :0 at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateObjectContract (System.Type objectType) [0x00035] in :0 at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateContract (System.Type objectType) [0x000c9] in :0 at Newtonsoft.Json.Serialization.DefaultContractResolver.ResolveContract (System.Type type) [0x00038] in :0 at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.GetContractSafe (System.Type type) [0x00005] in :0 at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateList (IList list, Newtonsoft.Json.JsonReader reader, Newtonsoft.Json.Serialization.JsonArrayContract contract, Newtonsoft.Json.Serialization.JsonProperty containerProperty, System.String id) [0x00052] in :0 at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateList (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, System.Object existingValue, System.String id) [0x000dc] in :0 at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue) [0x0007f] in :0 at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.SetPropertyValue (Newtonsoft.Json.Serialization.JsonProperty property, Newtonsoft.Json.JsonConverter propertyConverter, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerProperty, Newtonsoft.Json.JsonReader reader, System.Object target) [0x00061] in :0 at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject (System.Object newObject, Newtonsoft.Json.JsonReader reader, Newtonsoft.Json.Serialization.JsonObjectContract contract, Newtonsoft.Json.Serialization.JsonProperty member, System.String id) [0x00220] in :0
That's a known bug. Use 7.0.1 until 8.0.2 is released - https://github.com/JamesNK/Newtonsoft.Json/issues/771
TFS build controller failed
I have my own TFS build controller but it is failing build with this error any idea what issue can be? Exception Message: The type initializer for 'Microsoft.Web.Deployment.DeploymentManager' threw an exception. (type TypeInitializationException) Exception Stack Trace: Server stack trace: at Microsoft.Web.Deployment.DeploymentProviderSettingCollection..ctor(String factoryName) at Microsoft.Web.Deployment.DeploymentProviderOptions..ctor(String factoryName) at Microsoft.Web.Deployment.DeploymentProviderOptions..ctor(DeploymentWellKnownProvider wellKnownProvider) at Microsoft.TeamFoundation.Deployment.Workflow.Activities.MSDeployWorker.RunCommand(String publishEndpoint, String targetSite, String userName, String password, String packagePath, String setParametersPath, Boolean allowUntrustedCertificates) at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs) at System.Runtime.Remoting.Messaging.StackBuilderSink.AsyncProcessMessage(IMessage msg, IMessageSink replySink) Exception rethrown at [0]: at System.Activities.Statements.Throw.Execute(CodeActivityContext context) at System.Activities.CodeActivity.InternalExecute(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager) at System.Activities.Runtime.ActivityExecutor.ExecuteActivityWorkItem.ExecuteBody(ActivityExecutor executor, BookmarkManager bookmarkManager, Location resultLocation) Inner Exception Details: Exception Message: The type initializer for 'Microsoft.Web.Deployment.BuiltInTypesCache' threw an exception. (type TypeInitializationException) Exception Stack Trace: at Microsoft.Web.Deployment.DeploymentProviderFactoryCollection.LoadFromRegistry() at Microsoft.Web.Deployment.DeploymentManager.LoadDeploymentManagerSettings() at Microsoft.Web.Deployment.DeploymentManager..cctor() Inner Exception Details: Exception Message: The provider 'Microsoft.Data.Tools.Schema.MsDeploy.MsDeployProviderFactory' could not be loaded. (type DeploymentException) Exception Stack Trace: at Microsoft.Web.Deployment.DeploymentProviderFactory.Create(Type type) at Microsoft.Web.Deployment.BuiltInTypesCache.InspectTypesForWebDeployAttributes(IEnumerable`1 types, String dllName) at Microsoft.Web.Deployment.BuiltInTypesCache..cctor() Inner Exception Details: Exception Message: The type 'Microsoft.Data.Tools.Schema.MsDeploy.MsDeployProviderFactory' could not be loaded. The configuration settings may not be valid. (type DeploymentException) Exception Stack Trace: at Microsoft.Web.Deployment.ReflectionHelper.CreateInstanceT at Microsoft.Web.Deployment.DeploymentProviderFactory.Create(Type type) Inner Exception Details: Exception Message: The type initializer for 'Microsoft.Data.Tools.Schema.MsDeploy.MsDeployProviderBaseProviderFactory' threw an exception. (type TypeInitializationException) Exception Stack Trace: at System.Runtime.Remoting.RemotingServices.AllocateUninitializedObject(RuntimeType objectType) at System.Runtime.Remoting.Activation.ActivationServices.CreateInstance(RuntimeType serverType) at System.Runtime.Remoting.Activation.ActivationServices.IsCurrentContextOK(RuntimeType serverType, Object[] props, Boolean bNewObj) at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) at System.Activator.CreateInstance(Type type, Boolean nonPublic) at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, StackCrawlMark& stackMark) at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) at System.Activator.CreateInstance(Type type, Object[] args) at Microsoft.Web.Deployment.ReflectionHelper.CreateInstanceT Inner Exception Details: Exception Message: Could not load file or assembly 'Microsoft.Data.Tools.Schema.Sql, Version=10.3.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified. (type FileNotFoundException) Exception Stack Trace: at Microsoft.Data.Tools.Schema.MsDeploy.MsDeployProviderBaseProviderFactory..cctor()
Comment out the line following line in AssemblyInfo.cs file. [assembly: AssemblyCulture("")] OR In Build definition, Change the configuration and platform according to the local machine. Try using x86 for a 32 bit CPU or according to the CPU of the machine. try both the solutions one by one. and see if it resolves the issue.