Quickly to get a feeling on azure, I created a webapi project which uses EF and Local DB and it has some crud operations.
Then I signed up to Azure, created a WebApp and then downloaded the publish profile.
Using VS 2013, deployed the application to Azure. Navigated to index.html everything is working fine.
The problem is when I try to execute a simple HttpGet (which returns the value from the LocalDB), I am getting the below stack trace.
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace/>
<InnerException>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Format of the initialization string does not conform to specification starting at index 0.
</ExceptionMessage>
<ExceptionType>System.ArgumentException</ExceptionType>
<StackTrace>
at System.Data.Common.DbConnectionOptions.GetKeyValuePair(String connectionString, Int32 currentPosition, StringBuilder buffer, Boolean useOdbcRules, String& keyname, String& keyvalue) at System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable parsetable, String connectionString, Boolean buildChain, Hashtable synonyms, Boolean firstKey) at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Hashtable synonyms, Boolean useOdbcRules) at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString) at System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous) at System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions) at System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key) at System.Data.SqlClient.SqlConnection.set_ConnectionString(String value) at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.<SetConnectionString>b__18(DbConnection t, DbConnectionPropertyInterceptionContext`1 c) at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.SetConnectionString(DbConnection connection, DbConnectionPropertyInterceptionContext`1 interceptionContext) at System.Data.Entity.Internal.LazyInternalConnection.InitializeFromConnectionStringSetting(ConnectionStringSettings appConfigConnection) at System.Data.Entity.Internal.LazyInternalConnection.Initialize() at System.Data.Entity.Internal.LazyInternalConnection.get_Connection() at System.Data.Entity.Internal.LazyInternalContext.get_Connection() at System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type contextType, DbProviderInfo modelProviderInfo, AppConfig config, DbConnectionInfo connectionInfo, Func`1 resolver) at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration, DbContext usersContext, DatabaseExistenceState existenceState, Boolean calledByCreateDatabase) at System.Data.Entity.MigrateDatabaseToLatestVersion`2.InitializeDatabase(TContext context) at System.Data.Entity.Internal.InternalContext.<>c__DisplayClassf`1.<CreateInitializationAction>b__e() at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action) at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization() at System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c) at System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input) at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action) at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase() at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() at System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator() at System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator() at WriteArrayOfBankModelToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , CollectionDataContract ) at System.Runtime.Serialization.CollectionDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle) at System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.DataContractSerializer.WriteObject(XmlWriter writer, Object graph) at System.Net.Http.Formatting.XmlMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content) at System.Net.Http.Formatting.XmlMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken) --- 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.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__1b.MoveNext()
</StackTrace>
</InnerException>
</Error>
I also see there are no options to create a LocalDb in Azure Website.
I initially guessed since I am using CodeFirst approach, Azure will automatically create the database for me.
EDIT: I have seeded the database and added some sample data to the localdb. The api works just fine in my local machine.
Any inputs on this please ?
You should use Azure SQL Database instead of local DB.
You will still use CodeFirst.
Here is how to do it :
Enable Migrations, create the database, add sample data and a data initializer
https://azure.microsoft.com/en-us/documentation/articles/web-sites-dotnet-rest-service-aspnet-api-sql-database/#enable-migrations-create-the-database-add-sample-data-and-a-data-initializer
If needed, you can jump to the top of the page to see the complete tuto starting from the Web API...
Related
Server Error in '/' Application.
Access to the path '$(sourceFolder)\Foundation\Articles\serialization' is denied.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.UnauthorizedAccessException: Access to the path '$(sourceFolder)\Foundation\Articles\serialization' is denied.
ASP.NET is not authorized to access the requested resource. Consider granting access rights to the resource to the ASP.NET request identity. ASP.NET has a base process identity (typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6 and IIS 7, and the configured application pool identity on IIS 7.5) that is used if the application is not impersonating. If the application is impersonating via , the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.
To grant ASP.NET access to a file, right-click the file in File Explorer, choose "Properties" and select the Security tab. Click "Add" to add the appropriate user or group. Highlight the ASP.NET account, and check the boxes for the desired access.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[UnauthorizedAccessException: Access to the path '$(sourceFolder)\Foundation\Articles\serialization' is denied.]
System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) +435
System.IO.Directory.InternalCreateDirectory(String fullPath, String path, Object dirSecurityObj, Boolean checkHost) +1436
System.IO.Directory.InternalCreateDirectoryHelper(String path, Boolean checkHost) +98
Rainbow.Storage.SerializationFileSystemDataStore.InitializeRootPath(String rootPath) +346
Rainbow.Storage.SerializationFileSystemDataStore..ctor(String physicalRootPath, Boolean useDataCache, ITreeRootFactory rootFactory, ISerializationFormatter formatter) +236
lambda_method(Closure , Object[] ) +246
Configy.Containers.MicroContainer.Activate(Type type, KeyValuePair`2[] unmappedConstructorParameters) +841
Unicorn.Configuration.<>c__DisplayClass8_0.<RegisterConfigTypeInterface>b__3() +41
System.Lazy`1.CreateValue() +734
System.Lazy`1.LazyInitValue() +189
Unicorn.Data.ConfigurationDataStore.RegisterForChanges(Action`2 actionOnChange) +19
Unicorn.Data.DataProvider.UnicornDataProvider..ctor(ITargetDataStore targetDataStore, ISourceDataStore sourceDataStore, IPredicate predicate, IFieldFilter fieldFilter, IUnicornDataProviderLogger logger, IUnicornDataProviderConfiguration dataProviderConfiguration, ISyncConfiguration syncConfiguration, PredicateRootPathResolver rootPathResolver) +549
lambda_method(Closure , Object[] ) +402
Configy.Containers.MicroContainer.Activate(Type type, KeyValuePair`2[] unmappedConstructorParameters) +841
Configy.Containers.MicroContainer.Resolve() +110
System.Linq.WhereSelectArrayIterator`2.MoveNext() +145
System.Linq.Buffer`1..ctor(IEnumerable`1 source) +284
System.Linq.Enumerable.ToArray(IEnumerable`1 source) +90
Unicorn.Data.DataProvider.UnicornSqlServerDataProvider..ctor(String connectionString) +222
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +223
Sitecore.Reflection.ReflectionUtil.CreateObject(Type type, Object[] parameters) +119
Sitecore.Configuration.DefaultFactory.CreateFromTypeName(XmlNode configNode, String[] parameters, Boolean assert) +108
Sitecore.Configuration.DefaultFactory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert, IFactoryHelper helper) +163
Sitecore.Configuration.DefaultFactory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert) +72
Sitecore.Configuration.DefaultFactory.CreateObject(String configPath, String[] parameters, Boolean assert) +703
Sitecore.Configuration.DefaultFactory.CreateFromReference(XmlNode configNode, String[] parameters, Boolean assert) +170
Sitecore.Configuration.DefaultFactory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert, IFactoryHelper helper) +116
Sitecore.Configuration.DefaultFactory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert) +72
Sitecore.Configuration.DefaultFactory.GetInnerObject(XmlNode paramNode, String[] parameters, Boolean assert) +947
Sitecore.Configuration.DefaultFactory.AssignProperties(XmlNode configNode, String[] parameters, Object obj, Boolean assert, Boolean deferred, IFactoryHelper helper) +545
Sitecore.Configuration.DefaultFactory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert, IFactoryHelper helper) +326
Sitecore.Configuration.DefaultFactory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert) +72
Sitecore.Configuration.DefaultFactory.CreateObject(String configPath, String[] parameters, Boolean assert) +703
Sitecore.Configuration.DefaultFactory.GetDatabase(String name, Boolean assert) +157
Sitecore.XA.Foundation.Multisite.Providers.SxaSiteProvider.GetSiteList() +51
Sitecore.XA.Foundation.Multisite.Providers.SxaSiteProvider.InitializeSites() +105
Sitecore.XA.Foundation.Multisite.Providers.SxaSiteProvider.GetSites() +18
System.Linq.<SelectManyIterator>d__17`2.MoveNext() +265
Sitecore.Sites.SiteCollection.AddRange(IEnumerable`1 sites) +221
Sitecore.Sites.SitecoreSiteProvider.GetSites() +258
Sitecore.Sites.DefaultSiteContextFactory.GetSites() +253
Sitecore.XA.Foundation.Multisite.SiteInfoResolver.get_Sites() +60
Sitecore.XA.Foundation.Multisite.Pipelines.Initialize.InitSiteManager.Process(PipelineArgs args) +85
(Object , Object ) +9
Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args) +490
Sitecore.Pipelines.DefaultCorePipelineManager.Run(String pipelineName, PipelineArgs args, String pipelineDomain, Boolean failIfNotExists) +236
Sitecore.Pipelines.DefaultCorePipelineManager.Run(String pipelineName, PipelineArgs args, String pipelineDomain) +22
Sitecore.Nexus.Web.HttpModule.Application_Start() +220
Sitecore.Nexus.Web.HttpModule.Init(HttpApplication app) +1165
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +584
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +168
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +277
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +369
[HttpException (0x80004005): Exception has been thrown by the target of an invocation.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +532
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +111
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +724
Iv tried suggestions taken from the following:
Problems with error: "Access to the path is denied."
1) Open Internet Information Systems (IIS) Manager
2) Expand the site you want to modify (hit the plus next to the name)
3) Right-click the directory where you would like to be able to write files and select Edit Permissions
4) Click on the Security tab
5) Click on Edit... under the group and users list
6) Select IIS_IUSRS from the "Groups or user names" list and add make sure the Allow checkbox is marked for Write.
ASP.NET is not authorized to access the requested resource when accessing temp folder
a really simple fix to solve my issue, in IIS I had to right click on Application Pools and set .NET Framework V4 to Integrated rather than classic/.
Another solution was to set the specific folder that was being accessed to read/write to the users that required it, this can be done by unique users or within an organization, a group of users
(https://stackoverflow.com/a/47503132/19587900)
(1) I have gone to wwwroot folder. Right-click and security tab. Provided IISUSER to set read and write permission to the wwwroot folder.
(2) Changed the application pool to the separate pool and set identity to Application pool Identity.
Iv tried other things but so far no success
Looks like you're trying to create a folder that starts with "$(sourceFolder)", that's not going to work well. Are you missing a variable definition like:
<sc.variable name="sourceFolder" set:value="c:\whatever" />
I'm having problems debugging my assembly using the PluginProfiler supplied with the PluginRegistrationTool. Once I mark the step as profiling and trigger it (Create an account) it shows the following error message:
Unhandled Exception:
System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: Unexpected Exception in the Plug-in ProfilerDetail:
<OrganizationServiceFault xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/xrm/2011/Contracts">
<ErrorCode>-2147220891</ErrorCode>
<ErrorDetails xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic">
<KeyValuePairOfstringanyType>
<d2p1:key>CallStack</d2p1:key>
<d2p1:value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:string"> at PluginProfiler.Plugins.ProfilerBase`1.InitializeProfiler(Dictionary`2 services, T operationContext, ProfilerPluginContext& context)
at PluginProfiler.Plugins.ProfilerPlugin.Execute(IServiceProvider serviceProvider)
at Microsoft.Crm.Sandbox.SandboxAppDomainHelper.<>c__DisplayClass8.<Execute>b__1()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Crm.Sandbox.SandboxAppDomainHelper.Execute(IOrganizationServiceFactory organizationServiceFactory, Dictionary`2 sandboxServices, String pluginTypeName, String pluginConfiguration, String pluginSecureConfig, IPluginExecutionContext requestContext, Boolean enablePluginStackTrace, Boolean chaosFailAppDomain)
at Microsoft.Crm.Sandbox.SandboxAppDomainHelper.Execute(IOrganizationServiceFactory organizationServiceFactory, Dictionary`2 sandboxServices, String pluginTypeName, String pluginConfiguration, String pluginSecureConfig, IPluginExecutionContext requestContext, Boolean enablePluginStackTrace, Boolean chaosFailAppDomain)
at Microsoft.Crm.Sandbox.SandboxWorker.Execute(SandboxCallInfo callInfo, SandboxPluginExecutionContext requestContext, Guid pluginAssemblyId, Int32 sourceHash, String assemblyName, Guid pluginTypeId, String pluginTypeName, String pluginConfiguration, String pluginSecureConfig, SandboxRequestCounter& workerCounter, Boolean returnTraceInfo)</d2p1:value>
</KeyValuePairOfstringanyType>
<KeyValuePairOfstringanyType>
<d2p1:key>OperationStatus</d2p1:key>
<d2p1:value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:string">3</d2p1:value>
</KeyValuePairOfstringanyType>
<KeyValuePairOfstringanyType>
<d2p1:key>SubErrorCode</d2p1:key>
<d2p1:value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:string">-2146233088</d2p1:value>
</KeyValuePairOfstringanyType>
</ErrorDetails>
<Message>Unexpected Exception in the Plug-in Profiler</Message>
<Timestamp>2017-09-20T11:11:16.7252255Z</Timestamp>
<ExceptionRetriable>false</ExceptionRetriable>
<ExceptionSource i:nil="true" />
<InnerFault i:nil="true" />
<OriginalException i:nil="true" />
<TraceText>
[PluginProfiler.Plugins: PluginProfiler.Plugins.ProfilerPlugin]
[585cb523-f29d-e711-81b0-000d3a22c45c: XXXXXXXX.Xrm.Plugins.BasicEntryPoints.GenericPlugin: Create of account (Profiler)]
An exception occurred during the initialization of the Plug-in Profiler.
Unhandled Exception: System.TypeLoadException: Inheritance security rules violated while overriding member: 'Castle.DynamicProxy.ProxyGenerationOptions.GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)'. Security accessibility of the overriding method must match the security accessibility of the method being overriden.
at System.Reflection.RuntimeAssembly.GetExportedTypes(RuntimeAssembly assembly, ObjectHandleOnStack retTypes)
at System.Reflection.RuntimeAssembly.GetExportedTypes()
at Microsoft.Xrm.Sdk.KnownTypesProvider.get_KnownOrganizationRequestResponseTypes()
at Microsoft.Xrm.Sdk.KnownTypesResolver.ResolveName(String typeName, String typeNamespace, Type declaredType, DataContractResolver knownTypeResolver)
at System.Runtime.Serialization.XmlObjectSerializerContext.ResolveDataContractFromDataContractResolver(XmlQualifiedName typeName, Type declaredType)
at System.Runtime.Serialization.XmlObjectSerializerContext.ResolveDataContractFromKnownTypes(String typeName, String typeNs, DataContract memberTypeContract, Type declaredType)
at System.Runtime.Serialization.XmlObjectSerializerContext.IsKnownType(DataContract dataContract, Type declaredType)
at System.Runtime.Serialization.XmlObjectSerializerContext.IsKnownType(DataContract dataContract, Dictionary`2 knownDataContracts, Type declaredType)
at System.Runtime.Serialization.KnownTypeDataContractResolver.TryResolveType(Type type, Type declaredType, DataContractResolver knownTypeResolver, XmlDictionaryString& typeName, XmlDictionaryString& typeNamespace)
at Microsoft.Xrm.Sdk.KnownTypesResolver.TryResolveType(Type type, Type declaredType, DataContractResolver knownTypeResolver, XmlDictionaryString& typeName, XmlDictionaryString& typeNamespace)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.ResolveType(Type objectType, Type declaredType, XmlDictionaryString& typeName, XmlDictionaryString& typeNamespace)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteTypeInfo(XmlWriterDelegator writer, DataContract contract, DataContract declaredContract)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithXsiTypeAtTopLevel(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle originalDeclaredTypeHandle, Type graphType)
at System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.XmlObjectSerializer.WriteObject(XmlDictionaryWriter writer, Object graph)
at Microsoft.Crm.Sandbox.SandboxUtility.SerializeDataContract[T](T dataContract, Assembly proxyTypesAssembly)
at Microsoft.Crm.Sandbox.SandboxOrganizationServiceWrapper.ExecuteInternal(OrganizationRequest request)
at Microsoft.Crm.Sandbox.SandboxOrganizationServiceWrapper.RetrieveInternal(String entityName, Guid id, ColumnSet columnSet)
at Microsoft.Crm.Sandbox.SandboxOrganizationServiceWrapper.Retrieve(String entityName, Guid entityId, ColumnSet columnSet)
at PluginProfiler.Plugins.PluginLoaderUtility.RefreshAssembly(IOrganizationService service, ProfilerConfiguration config, PluginInitializationContext context)
at PluginProfiler.Plugins.PluginLoaderUtility.RefreshPluginInitializationContext(IOrganizationServiceFactory factory, ProfilerConfiguration config, PluginInitializationContext currentContext)
at PluginProfiler.Plugins.ProfilerBase`1.InitializeProfiler(Dictionary`2 services, T operationContext, ProfilerPluginContext& context)
</TraceText>
</OrganizationServiceFault>
I'm using StructureMap as IoC container and StructureMap.AutoFactory, which requires Castle.Core. I'm using ILMerge to merge all assemblies into a single on. I'm using the following arguments to execute ILMerge:
/target:library
/out:"$outPath"
/log:"$logFile"
/keyfile:"${keyFile}"
/copyattrs
/wildcards
/targetplatform:"v4,${Env:ProgramFiles(x86)}\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.2"
and the following assemblies (left out my dlls):
"${targetDir}StructureMap.dll"
"${targetDir}StructureMap.AutoFactory.dll"
"${targetDir}Castle.Core.dll"
I'm really out of ideas and it would be great if someone finds the time to help me. Thanks in advance!
As per this article the Sandboxed environment in which plugins run prohibits the use of Reflection to access internal members. I'm not familiar with dynamics proxying per se, but it looks like creating types on the fly and potentially using reflection in the process may not be possible in the sandbox.
If you have an on-prem dev environment you could register the plugin outside the sandbox and see what happens.
Have created a web application with Ninject and .Net 4 (have tested both 4.0 and 4.5) intended for Azure. The application has been tested ok on Azure before adding database support to it. Locally it runs ok with database support on SQL Express. But when altering the connect string to the Azure one and deployes it, I get the following error message.
I do NOT have a parameterless constructor in the controller, as I understand that Ninject needs one which is parameterized to work.
Azure administrative console indicates successfull connections to database.
Can anyone give me a hint for what might be wrong? I have to admit that I am new to both Azure and Ninject, this is my training project :-)
[NotSupportedException: Model compatibility cannot be checked because the database does not contain model metadata. Model compatibility can only be checked for databases created using Code First or Code First Migrations.]
System.Data.Entity.Internal.ModelCompatibilityChecker.CompatibleWithModel(InternalContext internalContext, ModelHashCalculator modelHashCalculator, Boolean throwIfNoMetadata) +221
System.Data.Entity.DropCreateDatabaseIfModelChanges`1.InitializeDatabase(TContext context) +218
System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action) +66
System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization() +225
System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input) +208
System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action) +235
System.Data.Entity.Internal.InternalContext.ForceOSpaceLoadingForKnownEntityTypes() +65
System.Data.Entity.DbContext.System.Data.Entity.Infrastructure.IObjectContextAdapter.get_ObjectContext() +36
STT.data.Repository.UnitOfWork..ctor(IDatabaseFactory databaseFactory) +88
DynamicInjector34635b924a6c4e6ab03c67010341a739(Object[] ) +92
Ninject.Activation.Context.Resolve() +294
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +248
System.Linq.Enumerable.SingleOrDefault(IEnumerable`1 source) +300
System.Linq.WhereSelectArrayIterator`2.MoveNext() +82
System.Linq.Buffer`1..ctor(IEnumerable`1 source) +520
System.Linq.Enumerable.ToArray(IEnumerable`1 source) +103
Ninject.Activation.Providers.StandardProvider.Create(IContext context) +480
Ninject.Activation.Context.Resolve() +294
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +248
System.Linq.Enumerable.SingleOrDefault(IEnumerable`1 source) +300
System.Linq.WhereSelectArrayIterator`2.MoveNext() +82
System.Linq.Buffer`1..ctor(IEnumerable`1 source) +520
System.Linq.Enumerable.ToArray(IEnumerable`1 source) +103
Ninject.Activation.Providers.StandardProvider.Create(IContext context) +480
Ninject.Activation.Context.Resolve() +294
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +248
System.Linq.Enumerable.SingleOrDefault(IEnumerable`1 source) +300
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +78
[InvalidOperationException: An error occurred when trying to create a controller of type 'STT.web.Controllers.HomeController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +256
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +81
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +270
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +86
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +12551795
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288
Thanks, Jakub.
Your link helped me. It turnes out that the initialization of the database is different with Azure SQL Server and SQL Express.
I altered Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DataContext>());
to Database.SetInitializer(new DropCreateDatabaseAlways<DataContext>());
and then redeployed. Then it worked in Azure as well. Then I moved back to the previous one and redeployed once more. The issue seems to be the table "_MigrationHistory" that were created in addition to my datatables.
Now it seems to work, but a bit cumbersome I think.
Thanks again.
Looks like an issue with EF.
NotSupportedException: Model compatibility cannot be checked because the database does not contain model metadata. Model compatibility can only be checked for databases created using Code First or Code First Migrations.
EF 4 Code First: Model compatibility cannot be checked because the EdmMetadata type was not included in the model
I am using latest EF v5 release candidate as per announcement here.
My model is using mapping files via EntityTypeConfiguration ...
When I attempted to replace string property on my model with an enum (drop+recreate db), I was getting this exception:
System.NotSupportedException was unhandled by user code
Message=The enum or spatial property 'Category' on type 'Vehicle' cannot be mapped. Use DbModelBuilderVersion 'V5_0' or later to map enum or spatial properties.
Source=EntityFramework
StackTrace:
at System.Data.Entity.ModelConfiguration.Mappers.PropertyFilter.ValidatePropertiesForModelVersion(Type type, IEnumerable`1 explicitlyMappedProperties)
at System.Data.Entity.ModelConfiguration.Mappers.PropertyFilter.GetProperties(Type type, Boolean declaredOnly, IEnumerable`1 explicitlyMappedProperties, IEnumerable`1 knownTypes)
at System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.MapStructuralElements[TStructuralTypeConfiguration](Type type, ICollection`1 annotations, Action`2 propertyMappingAction, Boolean mapDeclaredPropertiesOnly, Func`1 structuralTypeConfiguration)
at System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.MapEntityType(Type type)
at System.Data.Entity.DbModelBuilder.<>c__DisplayClass7.<MapTypes>b__1(Type type)
at System.Linq.Enumerable.WhereListIterator`1.MoveNext()
at System.Data.Entity.ModelConfiguration.Utilities.IEnumerableExtensions.Each[T](IEnumerable`1 ts, Action`1 action)
at System.Data.Entity.DbModelBuilder.MapTypes(EdmModel model)
at System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.InternalContext.Initialize()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator()
at System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at WebApp.Controllers.VehiclesController.Get() in C:\WebApp\Controllers\VehiclesController.cs:line 35
at lambda_method(Closure , Object , Object[] )
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.Execute(HttpControllerContext controllerContext, IDictionary`2 arguments)
at System.Web.Http.Controllers.ApiControllerActionInvoker.<>c__DisplayClass2.<InvokeActionAsync>b__0()
at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)
InnerException:
I then tried decorating my MyAppDbContext with [DbModelBuilderVersion(DbModelBuilderVersion.Latest)] and was getting the same error...
Finnaly I tried [DbModelBuilderVersion(DbModelBuilderVersion.V5_0)] and I got another exception:
System.Data.MetadataException was unhandled by user code
Message=Schema specified is not valid. Errors:
(2,9) : warning 0005: Could not find schema information for the attribute 'Namespace'.
(2,41) : warning 0005: Could not find schema information for the attribute 'Alias'.
(2,54) : error 0005: The 'http://schemas.microsoft.com/ado/2009/02/edm/annotation:UseStrongSpatialTypes' attribute is not declared.
(2,2) : error 0010: The element Schema in namespace http://schemas.microsoft.com/ado/2009/11/edm was unexpected for the root element. The expected Schema in one of the following namespaces: http://schemas.microsoft.com/ado/2006/04/edm, http://schemas.microsoft.com/ado/2007/05/edm, http://schemas.microsoft.com/ado/2008/09/edm.
Source=System.Data.Entity
StackTrace:
at System.Data.Metadata.Edm.EdmItemCollection.LoadItems(IEnumerable`1 xmlReaders, IEnumerable`1 sourceFilePaths, SchemaDataModelOption dataModelOption, DbProviderManifest providerManifest, ItemCollection itemCollection, Boolean throwOnError)
at System.Data.Metadata.Edm.EdmItemCollection.Init(IEnumerable`1 xmlReaders, IEnumerable`1 filePaths, Boolean throwOnError)
at System.Data.Metadata.Edm.EdmItemCollection..ctor(IEnumerable`1 xmlReaders)
at System.Data.Entity.ModelConfiguration.Edm.EdmModelExtensions.ToEdmItemCollection(EdmModel model)
at System.Data.Entity.ModelConfiguration.Edm.Db.Mapping.DbDatabaseMappingExtensions.ToMetadataWorkspace(DbDatabaseMapping databaseMapping)
at System.Data.Entity.Internal.CodeFirstCachedMetadataWorkspace..ctor(DbDatabaseMapping databaseMapping)
at System.Data.Entity.Infrastructure.DbCompiledModel..ctor(DbModel model)
at System.Data.Entity.Infrastructure.DbModel.Compile()
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.InternalContext.Initialize()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator()
at System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at WebApp.Controllers.VehiclesController.Get() in C:\WebApp\Controllers\VehiclesController.cs:line 35
at lambda_method(Closure , Object , Object[] )
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.Execute(HttpControllerContext controllerContext, IDictionary`2 arguments)
at System.Web.Http.Controllers.ApiControllerActionInvoker.<>c__DisplayClass2.<InvokeActionAsync>b__0()
at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)
InnerException:
My Controller is an ApiController and the breaking line looks like this:
var vehicles = _db.Vehicles.ToList();
BTW, I am using ASP.NET MVC 4 beta + Web API on VS 2010 (w/ .NET 4).
Any ideas?
Enums and all other new EF 5.0 features are dependent on .NET 4.5 (VS11) - both currently in Beta. If you run EF 5.0 in VS 2010 you get mostly the same functionality as in EF 4.3.1 = no enums.
I know what this error is, how to fix it, etc.
My question is that I don't know why my current page I am developing is throwing this error when I am not using the foo class directly in any way, nor am I setting anything to the viewstate. I am using postbacks alot, but like I said, I am not storing anything in the viewstate etc one integer.
I am using nhibernate if that is relevant.
Any idea why I need to mark this classes as serializable that arent being used? Where should I start investigating?
[SerializationException: Type 'FlexiCommerce.Persistence.NH.ContentPersister' in Assembly 'FlexiCommerce.Persistence.NH, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.]
System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(RuntimeType type) +9434541
System.Runtime.Serialization.FormatterServices.GetSerializableMembers(Type type, StreamingContext context) +247
System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo() +160
System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder) +218
System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Write(WriteObjectInfo objectInfo, NameInfo memberNameInfo, NameInfo typeNameInfo) +388
System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck) +444
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header[] headers, Boolean fCheck) +133
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph) +13
System.Web.UI.ObjectStateFormatter.SerializeValue(SerializerBinaryWriter writer, Object value) +2937
[ArgumentException: Error serializing value 'Music#2' of type 'FlexiCommerce.Components.Category.']
System.Web.UI.ObjectStateFormatter.SerializeValue(SerializerBinaryWriter writer, Object value) +3252
System.Web.UI.ObjectStateFormatter.SerializeValue(SerializerBinaryWriter writer, Object value) +2276
[ArgumentException: Error serializing value 'System.Object[]' of type 'System.Object[].']
System.Web.UI.ObjectStateFormatter.SerializeValue(SerializerBinaryWriter writer, Object value) +3252
System.Web.UI.ObjectStateFormatter.Serialize(Stream outputStream, Object stateGraph) +116
System.Web.UI.ObjectStateFormatter.Serialize(Object stateGraph) +57
System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Serialize(Object state) +4
System.Web.UI.Util.SerializeWithAssert(IStateFormatter formatter, Object stateGraph) +37
System.Web.UI.HiddenFieldPageStatePersister.Save() +79
System.Web.UI.Page.SavePageStateToPersistenceMedium(Object state) +108
System.Web.UI.Page.SaveAllState() +315
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2492
Are you perhaps databinding objects of this kind? It's clearly gotten into page state somehow.
I would assume you have enabled some of the caching elements either for query caching, or enabled actual object graph caching of NHibernate (if so probably using the SysCacheProvider which is just HttpRuntime.Cache).
I would recommend regardless of caching usage or not to mark every Domain object as serializable as it's very reasonable at some point that it will either go over the wire or just into a ViewState/Session container.