Azure database with Ninject - c#

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

Related

Getting error 0004: Could not load System.Data.SqlServerCe.Entity.dll. Reinstall SQL Server Compact

I am working on a ASP.NET Web Pages site with SQL Server CE 4.0.
I believe my SQL Server CE 4.0 database is working fine. I can connect to it without any problems on my dev machine with and without Entity Framework.
Once I push the site to the server, I can connect to it fine without entity framework using this connection string:
<add name="StarterSite"
connectionString="Data Source=|DataDirectory|\StarterSite.sdf"
providerName="System.Data.SqlServerCe.4.0" />
My Entity Framework connection string looks like this:
<add name="StarterSiteEntities"
connectionString="metadata=res://*/App_Code.ProductModel.csdl|res://*/App_Code.ProductModel.ssdl|res://*/App_Code.ProductModel.msl;provider=System.Data.SqlServerCe.4.0;provider connection string="data source=|DataDirectory|\StarterSite.sdf""
providerName="System.Data.EntityClient" />
When I try to make any EF database calls I get this error message:
Server Error in '/' Application.
Schema specified is not valid.
Errors:
App_Code.ProductModel.ssdl(2,88) : error 0004: Could not load System.Data.SqlServerCe.Entity.dll. Reinstall SQL Server Compact.
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.Data.MetadataException: Schema specified is not valid.
Errors:
App_Code.ProductModel.ssdl(2,88) : error 0004: Could not load System.Data.SqlServerCe.Entity.dll. Reinstall SQL Server Compact.
Source Error:
Line 23: using (var db = new StarterSiteEntities())
Line 24: {
Line 25: product = (from p in db.Products
Line 26: where p.ProductID == productId
Line 27: select p).FirstOrDefault();
Source File: c:\sites\www.foosite.org\Admin-RUF\Admin-Product-Edit.cshtml Line: 25
Stack Trace:
[MetadataException: Schema specified is not valid. Errors:
App_Code.ProductModel.ssdl(2,88) : error 0004: Could not load System.Data.SqlServerCe.Entity.dll. Reinstall SQL Server Compact. ]
System.Data.Metadata.Edm.Loader.ThrowOnNonWarningErrors() +8610213
System.Data.Metadata.Edm.Loader.LoadItems(IEnumerable1 xmlReaders, IEnumerable1 sourceFilePaths) +189
System.Data.Metadata.Edm.StoreItemCollection.Init(IEnumerable1 xmlReaders, IEnumerable1 filePaths, Boolean throwOnError, DbProviderManifest& providerManifest, DbProviderFactory& providerFactory, String& providerManifestToken, Memoizer2& cachedCTypeFunction) +182
System.Data.Metadata.Edm.StoreItemCollection..ctor(IEnumerable1 xmlReaders, IEnumerable1 filePaths) +244
System.Data.Metadata.Edm.StoreMetadataEntry.LoadStoreCollection(EdmItemCollection edmItemCollection, MetadataArtifactLoader loader) +90
System.Data.Metadata.Edm.StoreItemCollectionLoader.LoadItemCollection(StoreMetadataEntry entry) +16
System.Data.Metadata.Edm.MetadataCache.LoadItemCollection(IItemCollectionLoader1 itemCollectionLoader, T entry) +163
System.Data.Metadata.Edm.MetadataCache.GetOrCreateStoreAndMappingItemCollections(String cacheKey, MetadataArtifactLoader loader, EdmItemCollection edmItemCollection, Object& entryToken) +191
System.Data.EntityClient.EntityConnection.LoadStoreItemCollections(MetadataWorkspace workspace, DbConnection storeConnection, DbProviderFactory factory, DbConnectionOptions connectionOptions, EdmItemCollection edmItemCollection, MetadataArtifactLoader artifactLoader) +246
System.Data.EntityClient.EntityConnection.GetMetadataWorkspace(Boolean initializeAllCollections) +586
System.Data.EntityClient.EntityConnection.InitializeMetadata(DbConnection newConnection, DbConnection originalConnection, Boolean closeOriginalConnectionOnFailure) +75
System.Data.EntityClient.EntityConnection.Open() +150
System.Data.Objects.ObjectContext.EnsureConnection() +75
System.Data.Objects.ObjectQuery1.GetResults(Nullable1 forMergeOption) +41
System.Data.Objects.ObjectQuery1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() +36
System.Linq.Enumerable.FirstOrDefault(IEnumerable1 source) +152
System.Data.Objects.ELinq.ObjectQueryProvider.b__1(IEnumerable1 sequence) +41
System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle(IEnumerable1 query, Expression queryRoot) +59
System.Data.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute(Expression expression) +133
System.Data.Entity.Internal.Linq.DbQueryProvider.Execute(Expression expression) +87
System.Linq.Queryable.FirstOrDefault(IQueryable1 source) +251
ASP._Page_admin_ruf_Admin_Product_Edit_cshtml.Execute() in c:\sites\www.foosite.org\Admin-RUF\Admin-Product-Edit.cshtml:25
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +198
System.Web.WebPages.WebPage.ExecutePageHierarchy(IEnumerable1 executors) +69
System.Web.WebPages.WebPage.ExecutePageHierarchy() +131
System.Web.WebPages.StartPage.RunPage() +17
System.Web.WebPages.StartPage.ExecutePageHierarchy() +64
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +78
System.Web.WebPages.WebPageHttpHandler.ProcessRequestInternal(HttpContextBase httpContext) +116
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18044
What am I doing wrong?
Deploy System.Data.SqlServerCe.Entity.dll with your app, It is in C:\Program Files (x86)\Microsoft SQL Server Compact Edition\v4.0\Desktop\System.Data.SqlServerCe.Entity on my PC.

Entity Framework v5 release candidate throws exceptions when using enums in 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.

Why am I getting a Specified Cast is not valid error?

I've developed an application with ASP.NET MVC 2, and after deploying it, I get an InvalidCastException:
Error/Exception: "Specified cast is not valid."
Stacktrace:
[InvalidCastException: Specified cast is not valid.]
System.Data.SqlClient.SqlBuffer.get_Time() +77
System.Data.SqlClient.SqlDataReader.GetTimeSpan(Int32 i) +56
Read_Question(ObjectMaterializer`1 ) +1740
System.Data.Linq.SqlClient.ObjectReader`2.MoveNext() +29
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +7667556
System.Linq.Enumerable.ToList(IEnumerable`1 source) +61
TestEnvironment.Managements.QuestionManager.GetquestionsByTestId(Int32 testId) in D:\ParallelMinds\Projects\TestApplication\TestEnvironment\TestEnvironment\Managements\QuestionManager.cs:131
TestEnvironment.Controllers.LoadTestController.Index(Nullable`1 testId) in D:\ParallelMinds\Projects\TestApplication\TestEnvironment\TestEnvironment\Controllers\LoadTestController.cs:31
lambda_method(ExecutionScope , ControllerBase , Object[] ) +86
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +178
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +24
System.Web.Mvc.<>c__DisplayClassd.<InvokeActionMethodWithFilters>b__a() +53
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +258
System.Web.Mvc.<>c__DisplayClassf.<InvokeActionMethodWithFilters>b__c() +20
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +193
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +300
System.Web.Mvc.Controller.ExecuteCore() +104
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +36
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +7
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__4() +34
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +53
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +30
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +7
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8681102
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Why am I getting this error only when I deploy the application? It works fine in my local development server, and I only get this exception on one page.
Without any more details I would guess that the table you are accessing on your deployment database is inconsistent with the table on your development database.
Maybe you have a column that is of a different type on your local machine.
Either that or there is some invalid data in the record you are retrieving in the deployment database.
The error Specified cast is not valid is encountered when one type cannot be directly cast to another.
Usually, this mistake is made when the programmer thinks they have one type, but actually have another. Take for example a textbox which has been constrained to only accept numbers. A programmer might well read the value, and later on make the mistake of expecting it to be a number
string myValue = myTextBox.Text;
// later
someComponent.ValueExpectingANumber = (int)myValue; // specified cast is not valid
in the above example, the number would have to be "Parsed" rather than cast.
It looks to me like something in your Read_Question method is filling in a field that's supposed to be SQL-compatible date or time value, and whatever the method is putting into the value is improperly formatted. The System.Data.SqlClient.SqlBuffer.get_Time() method tries to convert that value to a SQL date/time and throws an exception.
The first place I would look is in the Read_Question method.
If this happened when you published the DB, it could be that the culture is different for that server instance. For example, the differences in the english and american versions of the date.
Alternatively, if you are using DateTime.MinValue, the DateTime.MinValue differs from the range accepted by sql server; instead use the SqlDateTime object.
Can you post the code that is calling this method?
Matt

MVC 2 and ASP.NET 4 Request Validation Exception

I am working on an application that I inherited from another dev shop that I recently upgraded to MVC2/.NET 4 from MVC 1/.NET 2/3.5. Everything is working fine with the exception of one page. On this page there is an iframe that loads up an instance of TinyMCE and allows for inline editing of some HTML templates. On the hosting page there is a JavaScript event wired up to the submit button that, when clicked, grabs the innerHtml value of the iframe, converts it into JSON, and places it into a hidden form field.
As the form posts I get the infamous 'A potentially dangerous Request.Form value was detected..." Now I followed Microsoft's whitepaper and added
<httpRuntime requestValidationMode="2.0" />
To my web.config and decorated my Controller with
[ValidateInput(false)]
And I am still getting this error. The relevant stack is below.
[HttpRequestValidationException (0x80004005): A potentially dangerous Request.Form value was detected from the client (HtmlContent="...orrectly? <a href=\"*|ARCHIVE|...").]
System.Web.HttpRequest.ValidateString(String value, String collectionKey, RequestValidationSource requestCollection) +8730676
System.Web.HttpRequest.ValidateNameValueCollection(NameValueCollection nvc, RequestValidationSource requestCollection) +122
System.Web.HttpRequest.get_Form() +114
System.Web.HttpRequestWrapper.get_Form() +11
System.Web.Mvc.HttpRequestExtensions.GetHttpMethodOverride(HttpRequestBase request) +235
System.Web.Mvc.AcceptVerbsAttribute.IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) +119
System.Web.Mvc.<>c__DisplayClass11.<RunSelectionFilters>b__d(ActionMethodSelectorAttribute attr) +57
System.Linq.Enumerable.All(IEnumerable`1 source, Func`2 predicate) +145
System.Web.Mvc.ActionMethodSelector.RunSelectionFilters(ControllerContext controllerContext, List`1 methodInfos) +524
System.Web.Mvc.ActionMethodSelector.FindActionMethod(ControllerContext controllerContext, String actionName) +122
System.Web.Mvc.ReflectedControllerDescriptor.FindAction(ControllerContext controllerContext, String actionName) +182
System.Web.Mvc.ControllerActionInvoker.FindAction(ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, String actionName) +47
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +283
System.Web.Mvc.Controller.ExecuteCore() +136
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +111
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +39
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__4() +65
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +44
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +42
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +140
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +54
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +52
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8836913
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
Interestingly is that if I hook the BeginRequest method in the Global.asax which would seem to indicate that the code is running under the 2.0 mode of request validation since, if my understanding of .NET 4s request validation is correct, I would not be able to get to this method if the code was running under 4.0 validation model since it processes everything before BeginRequest.
Now I was able to circumvent this problem by calling escape() from a JavaScript function on the the value of the hidden form field but that is, obviously, a hack. Has anyone else experienced this issue or have any idea what I can do to properly disable Request Validation for this method on my controller?
Thanks!
Check if your "pages" section in web.config looks like:
<pages validateRequest="false" ...>...</pages>
if not try to add validateRequest attribute. It works for me cause I had the same problem few months ago.
edit: lol, I didn't see that it is so old post. but I leave my answear, cause maybe it helps someone else

What is causing these SQL casting errors on my ASP.NET MVC/AJAX site? [Video showing problem]

I'm frustrated... my site has suddenly become very unstable. So much so that hitting refresh over and over will cause it to crash. To investigate, I turned off all error handling so I could see some YSOD's.
Instead of trying to write it all out, I made a video showing the issue. You can see it here on YouTube.
Here's a copy of the stacktrace:
[InvalidCastException: Specified cast is not valid.]
System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult) +847
System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries) +113
System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) +344
System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute(Expression expression) +23
System.Linq.Queryable.Count(IQueryable`1 source) +240
MvcPaging.PagedList`1.Initialize(IQueryable`1 source, Int32 index, Int32 pageSize, Nullable`1 totalCount) in C:\Users\BikGame\Desktop\src\MvcPaging\PagedList.cs:63
MvcPaging.PagedList`1..ctor(IQueryable`1 source, Int32 index, Int32 pageSize, Nullable`1 totalCount) in C:\Users\BikGame\Desktop\src\MvcPaging\PagedList.cs:25
MvcPaging.PagedList`1..ctor(IQueryable`1 source, Int32 index, Int32 pageSize) in C:\Users\BikGame\Desktop\src\MvcPaging\PagedList.cs:19
MvcPaging.PagingExtensions.ToPagedList(IQueryable`1 source, Int32 pageIndex, Int32 pageSize) in C:\Users\BikGame\Desktop\src\MvcPaging\PagingExtensions.cs:63
ApoAds.Controllers.HomeController.Index() in C:\Users\BikGame\Documents\Visual Studio 2008\Projects\APOAds-MultiBaseBiz\Controllers\HomeController.cs:22
lambda_method(ExecutionScope , ControllerBase , Object[] ) +39
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +178
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +24
System.Web.Mvc.<>c__DisplayClassa.<InvokeActionMethodWithFilters>b__7() +53
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +258
System.Web.Mvc.<>c__DisplayClassc.<InvokeActionMethodWithFilters>b__9() +20
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +258
System.Web.Mvc.<>c__DisplayClassc.<InvokeActionMethodWithFilters>b__9() +20
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +193
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +382
System.Web.Mvc.Controller.ExecuteCore() +123
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +23
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +7
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext) +144
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext httpContext) +54
System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext httpContext) +7
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
On the page that's trying to load there are two ajax calls to views that hit the database, render a table and return html. Portions of the menu at the top of the site are pulled from the database and then cached to prevent multiple return trips. Hosting is on IIS6 in a medium trust, shared environment.
Crazy how it works and then stops working for 3-4 minutes and then works again... perhaps a sql connection hanging and then timing out after a few minutes?
Any ideas would be very greatly appreciated! Thanks in advance!
Update: added data access code
I'm using LINQ to SQL in a repository pattern. Here's a query that one of the AJAX calls is using.
public IQueryable<Ad> FindAdsPerBase(string baseName, AdStatus status)
{
return (from ad in _db.Ads
join b in _db.AdBases on ad.AdID equals b.AdID
where b.MilBase.BaseName.ToLower() == baseName.ToLower() && ad.Status == (byte)status
select ad).Distinct().OrderByDescending(x => x.DateEntered);
}
and it is called in the controller like so:
var ads = _db.FindAdsPerBase(MilBase, AdStatus.Active).Take(11);
You haven't given nearly enough information to troubleshoot, and (no offense) I'm not heading over to YouTube to watch a video. Here are some general troubleshooting steps I'd take and questions I'd ask myself:
When it fails, is it always the exact same exception? Or does it vary? If the same exception is always thrown then there might be a defect in your logic somewhere. If you get totally random exceptions then you may have a hardware or infrastructure issue.
First thing to do when you get LINQ to SQL exceptions is hook up SQL Profiler to see the exact query statement being sent to the server. Copy/paste that into SQL Management Studio and run it by hand. Look at the results and compare them to the data types of the object you're loading: is the query mapping an empty value to a non-nullable field? Maybe a query column is being mapped to a property of a different type?
If it works for 3-4 minutes, then stops for 3-4 minutes, then works again, look for any time-specific code in your project. Are you doing any caching? Maybe the issue is related to the behavior that occurs when the cache is stale versus when it's not stale, or vice versa. Maybe you have a date/time calculation that overflows or does something funky for certain inputs?
Hook up a debugger and have it catch the exception. Then walk up the stack trace and look at the program state during a failure. Compare it to the program state when the app is working correctly. Anything stand out?
You may have changed something in your database (like datatype of a column) without remembering to re-create your LINQ classes. Thus LINQ to SQL may be causing that casting exception.

Categories

Resources