Editing an object in Entity Framework 6 - asp.net-mvc

I have an object Employee containing lots of information on an Employee, such as his Login, Name, LastName, e-mail address etc.
After retrieving all the information imputed on the edit page of an employee, I then call the following to update the object :
public Employee Edit(Employee objEmployee) // Work on EDIT
{
var Original = Get(objEmployee.Login);
_entities.Employees.Add(objEmployee);
_entities.SaveChanges();
return objEmployee;
}
Once it reaches SaveChanges() I get the following :
System.Data.Entity.Infrastructure.DbUpdateException was caught
HResult=-2146233087
Message=An error occurred while updating the entries. See the inner exception for details.
Source=EntityFramework
StackTrace:
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
at CRAWebSiteMVC.Models.EntityEmployeeManagerRepository.Edit(Employee objEmployee) in c:\Users\kade\Source\Workspaces\InfoCubedProjects\CRA\CRAWebSiteMVC\Models\Employee\EntityEmployeeManagerRepository.cs:line 26
at CRAWebSiteMVC.Models.EmployeeManagerService.Edit(Employee objEmployee) in c:\Users\kade\Source\Workspaces\InfoCubedProjects\CRA\CRAWebSiteMVC\Models\Employee\EmployeeManagerService.cs:line 113
InnerException: System.Data.Entity.Core.UpdateException
HResult=-2146233087
Message=An error occurred while updating the entries. See the inner exception for details.
Source=EntityFramework
StackTrace:
at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<Update>b__2(UpdateTranslator ut)
at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func`2 updateFunction)
at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update()
at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__d()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction)
at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClassb.<SaveChangesInternal>b__8()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction)
at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options)
at System.Data.Entity.Internal.InternalContext.SaveChanges()
InnerException: System.Data.SqlClient.SqlException
HResult=-2146232060
Message=Violation of PRIMARY KEY constraint 'PK_EMPLOYEE'. Cannot insert duplicate key in object 'dbo.Employee'.
The statement has been terminated.
Source=.Net SqlClient Data Provider
ErrorCode=-2146232060
Class=14
LineNumber=1
Number=2627
Procedure=""
Server=MMSDEVNEW\SQL2008
State=1
StackTrace:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext`1 c)
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues)
at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
InnerException:
Violation of PRIMARY KEY constraint 'PK_EMPLOYEE'. Cannot insert duplicate key in object 'dbo.Employee'.
What could be causing that, and how may I solve it?

You need to update the entity and not to re-insert it:
public Employee Edit(Employee objEmployee) // Work on EDIT
{
_entities.Employees.Attach(objEmployee);
var entity = _entities.Entry(objEmployee);
entry.State = EntityState.Modified; // Mark as modified
_entities.SaveChanges();
return objEmployee;
}

Related

Swagger not working have any recommerndation?

Not working Swagger Ui
500 : {"Message":"An error has occurred.","ExceptionMessage":"Invalid type owner for DynamicMethod.","ExceptionType":"System.ArgumentException","StackTrace":" at System.Reflection.Emit.DynamicMethod.Init(String name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] signature, Type owner, Module m, Boolean skipVisibility, Boolean transparentMethod, StackCrawlMark& stackMark)\r\n at System.Reflection.Emit.DynamicMethod..ctor(String name, Type returnType, Type[] parameterTypes, Type owner, Boolean skipVisibility)\r\n at Newtonsoft.Json.Utilities.DynamicReflectionDelegateFactory.CreateDynamicMethod(String name, Type returnType, Type[] parameterTypes, Type owner)\r\n at Newtonsoft.Json.Utilities.DynamicReflectionDelegateFactory.CreateDefaultConstructor[T](Type type)\r\n at Newtonsoft.Json.Serialization.DefaultContractResolver.GetDefaultCreator(Type createdType)\r\n at Newtonsoft.Json.Serialization.DefaultContractResolver.InitializeContract(JsonContract contract)\r\n at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateArrayContract(Type objectType)\r\n at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateContract(Type objectType)\r\n at Newtonsoft.Json.Serialization.DefaultContractResolver.ResolveContract(Type type)\r\n at Swashbuckle.Swagger.SchemaRegistry.CreateInlineSchema(Type type)\r\n at Swashbuckle.Swagger.SchemaRegistry.GetOrRegister(Type type)\r\n at Swashbuckle.Swagger.SwaggerGenerator.CreateParameter(String location, ApiParameterDescription paramDesc, SchemaRegistry schemaRegistry)\r\n at Swashbuckle.Swagger.SwaggerGenerator.<>c__DisplayClass12.b__11(ApiParameterDescription paramDesc)\r\n at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext()\r\n at System.Collections.Generic.List1..ctor(IEnumerable1 collection)\r\n at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source)\r\n at Swashbuckle.Swagger.SwaggerGenerator.CreateOperation(ApiDescription apiDesc, SchemaRegistry schemaRegistry)\r\n at Swashbuckle.Swagger.SwaggerGenerator.CreatePathItem(IEnumerable1 apiDescriptions, SchemaRegistry schemaRegistry)\r\n at Swashbuckle.Swagger.SwaggerGenerator.<>c__DisplayClass7.<GetSwagger>b__4(IGrouping2 group)\r\n at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable1 source, Func2 keySelector, Func2 elementSelector, IEqualityComparer1 comparer)\r\n at Swashbuckle.Swagger.SwaggerGenerator.GetSwagger(String rootUrl, String apiVersion)\r\n at Swashbuckle.Application.SwaggerDocsHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n at System.Net.Http.HttpMessageInvoker.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n at System.Web.Http.Dispatcher.HttpRoutingDispatcher.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n at System.Net.Http.DelegatingHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n at System.Web.Http.HttpServer.d__0.MoveNext()"} http://localhost:5352/swagger/docs/v1
When I got this error, it was because I had an error/omission in my ResponseType definition (WebApi). The compiler was fine with it, but Swagger wasn't.
Failed
[ResponseType(typeof(IEnumerable<>))]
Worked
[ResponseType(typeof(IEnumerable<string>))]

Exception while passing string to DocumentHelper.GetDocuments().Where()

I'm trying to get nodes like this:
DocumentHelper.GetDocuments()
.Where("NodeParentID == 25 && NodeLevel == 2")
but getting an exception:
Incorrect syntax near '='. at
System.Data.SqlClient.SqlConnection.OnError(SqlException exception,
Boolean breakConnection, Action1 wrapCloseInAction) at
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,
SqlCommand cmdHandler, SqlDataReader dataStream,
BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject
stateObj, Boolean& dataReady) at
System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() at
System.Data.SqlClient.SqlDataReader.get_MetaData() at
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,
RunBehavior runBehavior, String resetOptionsString, Boolean
isInternal, Boolean forDescribeParameterEncryption, Boolean
shouldCacheForAlwaysEncrypted) at
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean
async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry,
SqlDataReader ds, Boolean describeParameterEncryptionRequest) at
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method, TaskCompletionSource1 completion, Int32 timeout, Task& task,
Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) at
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method) at
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior
behavior, String method) at
System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset,
DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String
srcTable, IDbCommand command, CommandBehavior behavior) at
System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32
startRecord, Int32 maxRecords, String srcTable, IDbCommand command,
CommandBehavior behavior) at
System.Data.Common.DbDataAdapter.Fill(DataSet dataSet) at
CMS.DataEngine.AbstractDataConnection.ExecuteQuery(String queryText,
QueryDataParameters queryParams, QueryTypeEnum queryType, Boolean
requiresTransaction) --- End of inner exception stack trace ---
at CMS.DataEngine.AbstractDataConnection.HandleError(String queryText,
Exception ex) at
CMS.DataEngine.AbstractDataConnection.ExecuteQuery(String queryText,
QueryDataParameters queryParams, QueryTypeEnum queryType, Boolean
requiresTransaction) at
CMS.DataEngine.GeneralConnection.RunQuery(QueryParameters query) at
CMS.DataEngine.GeneralConnection.RunQueryWithRetry(QueryParameters
query, Int32 retryCount) at
CMS.DataEngine.GeneralConnection.ExecuteQuery(QueryParameters query,
Int32& totalRecords) at
CMS.DataEngine.DataQueryBase1.GetDataFromDBInternal() at
CMS.DataEngine.DataQueryBase1.GetDataFromDB() at
CMS.DataEngine.DataQueryBase1.GetData() at
CMS.DataEngine.DataQueryBase1.get_Result() at
CMS.DataEngine.DataQueryBase1.GetResults(IDataQuery query, Int32&
totalRecords) at CMS.DataEngine.DataQueryBase1.GetDataFromDB()
at
CMS.DocumentEngine.DocumentQueryProperties.GetDataInternal(IDocumentQuery
query, Func1 baseGetDataMethod, Action1 setTotalRecords) at
CMS.DataEngine.DataQueryBase1.GetData() at
CMS.DataEngine.DataQueryBase1.get_Result() at
CMS.DataEngine.MultiObjectQueryBase3.EnsureTypedResult() at
CMS.DataEngine.MultiObjectQueryBase3.GetEnumerator() at
System.Collections.Generic.List1..ctor(IEnumerable1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
What am I doing wrong?
Your SQL syntax is incorrect in your "WHERE" clause. You're trying to use C# syntax in a place where you need to use T-SQL
Incorrect:
DocumentHelper.GetDocuments().Where("NodeParentID == 25 && NodeLevel == 2");
Correct:
DocumentHelper.GetDocuments().Where("NodeParentID = 25 AND NodeLevel = 2");
== is a c# syntax, SQL uses just one =.
You should do your where conditions like this:
.Where("NodeParentID", QueryOperator.Equals, 25)
.Where("NodeLevel ", QueryOperator.Equals, 7);

Sqlexpress Format of the initialization string does not conform to specification starting at index 0

i have two connectionStrings:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-Eriksson-Stilladser-20170117090241.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />
<add name="dc1" connectionString="Data Source=ERIKSDC01\SQLExpress; Integrated Security=True" providerName="System.Data.SqlClient" />
Where DefaultConnection is my localTest Database, (works fine)
and dc1 is my SqlExpress server. Worked fine until today now when i run my Package Manager Console
Update-database -connectionString dc1
I get this
cmdlet Update-Database at command pipeline position 1
Supply values for the following parameters:
ConnectionProviderName:
i type in System.Data.SqlClient, and then i get this Error:
System.ArgumentException: Format of the initialization string does not conform to specification starting at index 0.
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.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration)
at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.GetMigrator()
at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run()
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration, Boolean force)
at System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0()
at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
Format of the initialization string does not conform to specification starting at index 0.

How to configure mvc mini profiler with Linq to SQL?

I have configured mini profiler with asp.net mvc application. I also want to profile my db so I hooked it with L2S datacontext as in this example.
It is working fine for some queries but on other queries I find null reference exception. When I attached the source code to debug I found out that
internal void AddSqlTiming(SqlTiming stats)
{
Head.AddSqlTiming(stats);
}
Head Property in above method is null in MiniProfiler.cs at line 198. Any idea why?
EDIT: Following method returns me the datacontext object
public static EvoletDataContext Get()
{
var connection = ProfiledDbConnection.Get(new SqlConnection(ConfigurationManager.ConnectionStrings["evoletworksConnectionString"].ToString()));
//var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["evoletworksConnectionString"].ToString());
//return new EvoletDataContext(connection);
return DataContextUtils.CreateDataContext<EvoletDataContext>(connection);
}
And below is the query on which miniprofiler crashes for the first time
public sysModule GetModuleHead(string actionName)
{
var val = (from mod in db.sysModules
where
mod.ModuleActionResult.ToLower().Equals(actionName.ToLowerInvariant())
select mod).SingleOrDefault();
return val;
}
For more detail, please see this question as well. I tried but failed to reproduce problem in demo project.
Edit 2: Here is the stacktrace:
[NullReferenceException: Object reference not set to an instance of an object.]
MvcMiniProfiler.MiniProfiler.AddSqlTiming(SqlTiming stats) in C:\Dev\mvc-mini-profiler\MvcMiniProfiler\MiniProfiler.cs:241
MvcMiniProfiler.SqlTiming..ctor(DbCommand command, ExecuteType type, MiniProfiler profiler) in C:\Dev\mvc-mini-profiler\MvcMiniProfiler\SqlTiming.cs:66
MvcMiniProfiler.SqlProfiler.ExecuteStartImpl(DbCommand command, ExecuteType type) in C:\Dev\mvc-mini-profiler\MvcMiniProfiler\SqlProfiler.cs:50
MvcMiniProfiler.SqlProfilerExtensions.ExecuteStart(SqlProfiler sqlProfiler, DbCommand command, ExecuteType type) in C:\Dev\mvc-mini-profiler\MvcMiniProfiler\SqlProfiler.cs:95
MvcMiniProfiler.Data.ProfiledDbCommand.ExecuteDbDataReader(CommandBehavior behavior) in C:\Dev\mvc-mini-profiler\MvcMiniProfiler\Data\ProfiledDbCommand.cs:149
System.Data.Common.DbCommand.ExecuteReader() +12
System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult) +724
System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries) +189
System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) +659
System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute(Expression expression) +59
System.Linq.Queryable.SingleOrDefault(IQueryable`1 source) +265
UserManagement.Models.FilterRepository.GetModuleHead(String actionName) in D:\Evolet\UserManagement\UserManagement\Models\FilterRepository.cs:14
UserManagement.Models.DummyAttrib.OnAuthorization(AuthorizationContext filterContext) in D:\Evolet\UserManagement\UserManagement\Models\Filters.cs:30
Glimpse.Net.Plumbing.GlimpseAuthorizationFilter.OnAuthorization(AuthorizationContext filterContext) +157
System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor) +149
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +830
System.Web.Mvc.Controller.ExecuteCore() +135
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +232
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +39
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +68
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.<>c__DisplayClasse.<EndProcessRequest>b__d() +61
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +31
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +56
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +110
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +690
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +194
This used to happen if you had a ProfiledDbConnection in play and the actual profiler was set to null.
In general we avoid serving our internal consumers a ProfiledDbConnection if the current request is not profiled ... this means everything is just a bit faster.
Unfortunately, this can be sometimes tricky to do with EF and L2S. To overcome this I just checked in a change that allows you to use the Profiling bespoke objects even if no profiler is in play.
Nonetheless, my recommendation remains that you should be using raw connections where possible when you are not profiling.
Looks like this issue has finally been fixed in the latest commit:
https://github.com/SamSaffron/MiniProfiler/commit/bcea578dd47d7f9ccf1f495cf67c360cdece5f2a

Microsoft not disposing of their own objects?

EDIT: Server is MOSS 2007 Enterprise, running SP1 and all patches up to, but not including, SP2. SP2 is coming soon.
In one of my SharePoint apps, I am getting this warning & stacktrace over and over (with different GUIDS): since it's only one of my apps, I assume there's something in my project's code, but SPDisposeCheck returns clean, and there's nothing in the logs that point to my code.
Any ideas on how I can track this down?
Error I'm getting:
Potentially excessive number of
SPRequest objects (9) currently
unreleased on thread 1. Ensure that
this object or its parent (such as an
SPWeb or SPSite) is being properly
disposed. Allocation Id for this
object:
{1DFFC1ED-E69E-4580-8D7B-45EDB5C49188}
Stack trace of current allocation:
at Microsoft.SharePoint.SPRequestManager.Add(SPRequest request, Boolean shareable)
at Microsoft.SharePoint.SPGlobal.CreateSPRequestAndSetIdentity(Boolean bNotGlobalAdminCode, String strUrl, Boolean bNotAddToContext, Byte[] UserToken, String userName, Boolean bIgnoreTokenTimeout, Boolean bAsAnonymous)
at Microsoft.SharePoint.SPWeb.InitializeSPRequest()
at Microsoft.SharePoint.SPWeb.EnsureSPRequest()
at Microsoft.SharePoint.SPWeb.get_Request()
at Microsoft.SharePoint.SPWeb.GetFileOrFolderProperties(String strUrl, ListDocsFlags listDocsFlags, Boolean throwException)
at Microsoft.SharePoint.SPFile.PropertiesCore(Boolean throwException)
at Microsoft.SharePoint.SPFile.get_Properties()
at Microsoft.SharePoint.SPFile.get_Level()
at Microsoft.SharePoint.Publishing.WebControls.ConsoleXmlUtilities.configFile(String myUniqueId, SPFileLevel level)
at Microsoft.SharePoint.Publishing.WebControls.ConsoleXmlUtilities.ConfigurationXml(String configProvider, Boolean isBuiltInConfigFile)
at Microsoft.SharePoint.Publishing.WebControls.ConsoleXmlUtilities.GetConsoleNodeCollection(String configXml, ConsoleNode prePopulatedRootNode)
at Microsoft.SharePoint.Publishing.WebControls.ConsoleXmlUtilities.GetConsoleNodeCollection(String configXml)
at Microsoft.SharePoint.Publishing.WebControls.ConsoleXmlUtilities.GetConsoleNodeCollectionFromXmlFile(String configName, Boolean isBuiltInConfigFile)
at Microsoft.SharePoint.Publishing.WebControls.XmlConsoleDataSource.LoadTreeFromConfigXml()
at Microsoft.SharePoint.Publishing.WebControls.XmlConsoleDataSource.OnLoad(EventArgs e)
at Microsoft.SharePoint.Publishing.WebControls.ConsoleDataSource.ForceInitLoad(EventArgs e)
at Microsoft.SharePoint.Publishing.WebControls.PublishingSiteActionsMenuCustomizer.OnLoad(EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context)
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at Microsoft.SharePoint.Publishing.TemplateRedirectionPage.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
at System.Web.HttpApplication.ApplicationStepManager.ResumeSteps(Exception error)
at System.Web.HttpApplication.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
at System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr)
at System.Web.HttpRuntime.ProcessRequestNoDemand(HttpWorkerRequest wr)
at System.Web.Hosting.ISAPIRuntime.ProcessRequest(IntPtr ecb, Int32 iWRType)
This is apparently expected behavior.

Resources