SimpleInjector and System.Web.Mvc.Async threads - dependency-injection

I asked before a question here, and I read this question/answers about multi-threading and I know those solutions. But today I get a new problem. When we are using commands (or where we can access the original code to manage and modify it) the async-decorator that suggested in above answers works. But when MVC creates a new thread itself, what can we do? e.g. I have a custom role provider (works with DbContext), and I get this error:
The operation cannot be completed because the DbContext has been disposed.
And here is stack trace:
[InvalidOperationException: The operation cannot be completed because the DbContext has been disposed.]
System.Data.Entity.Internal.InternalContext.CheckContextNotDisposed() +67
System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +34
System.Data.Entity.Internal.Linq.DbQueryProvider.Execute(Expression expression) +22
System.Linq.Queryable.Any(IQueryable1 source, Expression1 predicate) +265
MyProject.MyRoleProvider.IsUserInRole(String username, String roleName) in ...
System.Web.Security.Roles.IsUserInRole(String username, String roleName) +263
MyProject.MyPrincipal.IsInRole(String role) in ...
System.Linq.Enumerable.Any(IEnumerable1 source, Func2 predicate) +146
System.Web.Mvc.AuthorizeAttribute.AuthorizeCore(HttpContextBase httpContext) +200
System.Web.Mvc.AuthorizeAttribute.OnAuthorization(AuthorizationContext filterContext) +159
System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor) +96
System.Web.Mvc.Async.<>c__DisplayClass25.b__1e(AsyncCallback asyncCallback, Object asyncState) +446
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +302
System.Web.Mvc.<>c__DisplayClass1d.b__17(AsyncCallback asyncCallback, Object asyncState) +30
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +382
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +317
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +15
System.Web.Mvc.<>c__DisplayClass8.b__2(AsyncCallback asyncCallback, Object asyncState) +71
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +249
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
As you can see, MyProject.MyRoleProvider.IsUserInRole invoked asynchronously, which I did not start it and its invoking async by MVC itself. So I have not any control on it. My provider ctor is:
public MyRoleProvider() {
_context = MyIoCWrapper.GetService();
}
It seems when MyRoleProvider instantiated, HttpContext is not null, and when IsInRole called, HttpContext is null.
If I want to start a new life scope, it will be used just once, and if MVC starts a new thread, I will have a new DbContext too. I confused to finding a solution. Have you any one?
How can I start a new life scope for all background threads -I start them or MVC starts them?

Your problem is in fact unrelated to running controllers asynchronously, but is a general problem of controlling the lifetime of objects.
You probably registered your MyRoleProvider in the web.config of the application, or perhaps registered it through code. Eitherway, the MyRoleProvider is a singleton, there is just a single instance of that class during the lifetime of the application.
The MyRoleProvider however depends on a DbContext which has a lifestyle that is shorter (Per Web Request or hybrid in your case), which means you can't cache that DbContext during the lifetime of your MyRoleProver, since that would 'promote' the lifestyle of that DbContext to singleton as well. The _context = MyIoCWrapper.GetService(); line seems to indicate that you are caching that DbContext.
In this case you will have to resolve the DbContext instance on each method call. So instead, your IsUserInRole would look something like this:
public bool IsUserInRole(String username, String roleName)
{
var context = MyIoCWrapper.GetService();
return context.Roles
.Any(r => r.Name == roleName && r.User.Name == username);
}

Related

Catel UIVisualizerService issue with Syncfusion sfDatagrid

I have created a project that makes use of Catel, Entity Framework 6 and Syncfusion Community Edition. Specifically I am using the sfDataGrid from Syncfusion.
I have come across an issue that has me completely stumped, maybe someone out there could point me in the right direction.
I have a Catel UserControl with a sfDataGrid in it. The ViewModel has an ObservableCollection (Catel Property) of the data I am using as the ItemsSource for the sfDataGrid. I have filtering enabled on the sfDataGrid. Here is the code for the sfDataGrid:
<sync:SfDataGrid
x:Name="ItemsDataGrid"
ItemsSource="{Binding MyItems, Mode=OneWay}"
SelectedItem="{Binding MyItem, Mode=TwoWay}"
AutoGenerateColumns="False"
AllowFiltering="True"
AllowResizingColumns="True"
GridCopyOption="IncludeHeaders"
GridPasteOption="None"
ShowGroupDropArea="True"
ShowRowHeader="True"
DataFetchSize="50">
<!-- Columns -->
</sync:SfDataGrid>
I add a new Item to the collection on a different view and then I save it to the datacontext and refresh the list:
private async void OnNewMyItemExecute()
{
MyItem= new MyItem();
MyItemsRepository.Add(MyItem);
var myItemsViewModel = TypeFactory
.Default
.CreateInstanceWithParametersAndAutoCompletion<myItemsViewModel >(MyItem); //the construction has parameters for IUIVisualizerService, IPleaseWaitService, etc.
if (await _UIVisualizerService.ShowDialogAsync(myItemsViewModel) ?? true)
{
var myItem= myItemsViewModel.MyItem;
await InitializeAsync();
MyItem = myItem;
}
else
{
_UnitOfWorkService.Rollback(); //just undo some changes
MyItem = null;
}
UnitOfWork.SaveChanges();
}
Creating a new Item is not a problem at all, the thing that is weird is that after I created a new Item and then attempt to filter grid on any column of the sfDataGrid (click the filter button in the column header, a filter popup opens, enter a value in the criteria textbox and click 'OK'), I get this:
MyProject.vshost.exe Warning: 0 : 17:57:49:075 => [WARNING]
[Catel.Services.UIVisualizerService] [8] An error occurred, returning
null since we don't know the result | [TargetInvocationException]
System.Reflection.TargetInvocationException: Exception has been thrown
by the target of an invocation. --->
System.Reflection.TargetInvocationException: Exception has been thrown
by the target of an invocation. ---> System.InvalidCastException:
Unable to cast object of type 'MyProject.Domain.MyItem' to type
'System.Data.Entity.DynamicProxies.MyItem_4CA6F59AB53174892ED9EFBC1D3CC07B862579FC3C5733C6CF4DE857907CFF9C'.
at lambda_method(Closure , MyItem ) --- End of inner exception
stack trace --- at System.RuntimeMethodHandle.InvokeMethod(Object
target, Object[] arguments, Signature sig, Boolean constructor) at
System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj,
Object[] parameters, Object[] arguments) at
System.Delegate.DynamicInvokeImpl(Object[] args) at
System.Delegate.DynamicInvoke(Object[] args) at
Syncfusion.Data.QueryableCollectionView.<>c__DisplayClass3.b__1(Object
o) at Syncfusion.Data.QueryableCollectionView.FilterRecord(Object
record) at
Syncfusion.Data.EnumerableRecordsWrapper..ctor(IEnumerable source,
CollectionViewAdv view) at
Syncfusion.Data.EnumerableRecordsWrapper.CreateNew(IEnumerable source,
CollectionViewAdv view) at
Syncfusion.Data.QueryableCollectionView.CreateRecords() at
Syncfusion.Data.CollectionViewAdv.EnsureInitialized() at
Syncfusion.Data.CollectionViewAdv.get_Records() at
Syncfusion.Data.CollectionViewAdv.EnsureRecordsInitialized() at
Syncfusion.Data.CollectionViewAdv.Refresh() at
Syncfusion.Data.QueryableCollectionView.RefreshFilter() at
Syncfusion.Data.CollectionViewAdv.ApplyFilters() at
Syncfusion.Data.CollectionViewAdv.set_FilterPredicates(ObservableCollection1
value) at Syncfusion.UI.Xaml.Grid.GridModel.FilterColumn(GridColumn
column, List1 filterPredicates) at
Syncfusion.UI.Xaml.Grid.GridFilterControl.RefreshFilter() at
Syncfusion.UI.Xaml.Grid.GridFilterControl.b__10(Object
s, RunWorkerCompletedEventArgs e) at
System.ComponentModel.BackgroundWorker.OnRunWorkerCompleted(RunWorkerCompletedEventArgs
e) at
System.ComponentModel.BackgroundWorker.AsyncOperationCompleted(Object
arg) at
System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate
callback, Object args, Int32 numArgs) at
System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source,
Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.DispatcherOperation.InvokeImpl() at
System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object
state) at
System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state) at
System.Windows.Threading.DispatcherOperation.Invoke() at
System.Windows.Threading.Dispatcher.ProcessQueue() at
System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32
msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at
MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam,
IntPtr lParam, Boolean& handled) at
MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) at
System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate
callback, Object args, Int32 numArgs) at
System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source,
Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at
System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority
priority, TimeSpan timeout, Delegate method, Object args, Int32
numArgs) at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd,
Int32 msg, IntPtr wParam, IntPtr lParam) at
MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg) at
System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame
frame) at
System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Window.ShowHelper(Object booleanBox) at
System.Windows.Window.Show() at System.Windows.Window.ShowDialog()
--- End of inner exception stack trace --- at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[]
arguments, Signature sig, Boolean constructor) at
System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj,
Object[] parameters, Object[] arguments) at
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags
invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[]
parameters) at
Catel.Services.UIVisualizerService.<>c__DisplayClass23_0.b__0()
in
C:\CI_WS\Ws\86058\Source\Catel\src\Catel.MVVM\Catel.MVVM.Shared\Services\UIVisualizerService.cs:line
499
This is the method of UIVisualizerService with Line 499:
protected virtual bool? ShowWindow(FrameworkElement window, bool showModal)
{
if (showModal)
{
var showDialogMethodInfo = window.GetType().GetMethodEx("ShowDialog");
if (showDialogMethodInfo != null)
{
// Child window does not have a ShowDialog, so not null is allowed
bool? result = null;
window.Dispatcher.InvokeIfRequired(() =>
{
// Safety net to prevent crashes when this is the main window
try
{
result = showDialogMethodInfo.Invoke(window, null) as bool?; //Line 499
}
catch (Exception ex)
{
Log.Warning(ex, "An error occurred, returning null since we don't know the result");
}
});
return result;
}
Log.Warning("Method 'ShowDialog' not found on '{0}', falling back to 'Show'", window.GetType().Name);
}
I have tried opening MyItemsView with .ShowAsync(), .ShowDialogAsync() and before I upgraded to Catel 4.4 I also used .ShowDialog(), but it made no difference. I could turn Proxy Creation off in EF, but that would cause a lot of changes I have to make in my project (no more lazy loading for me, and that is not an option). I do believe the problem being the new Item I add not being a Dynamic Proxy, and getting it to be a Dynamic Proxy would probably solve the issue, but I have tried loading all the data from the DbContext again, but it also does not solve the problem.
Any advice would be appreciated.
The issue is this:
System.InvalidCastException: Unable to cast object of type 'MyProject.Domain.MyItem' to type 'System.Data.Entity.DynamicProxies.MyItem_4CA6F59AB53174892ED9EFBC1D3CC07B862579FC3C5733C6CF4DE857907CFF9C'.
The reason is, of course, that you are trying to cast a base type to a derived type (which it simply isn't). That this eventually results in the window closing is because an exception happens, but that isn't the real problem.
This exception occurs in the FilterRecord method of the grid. I am not sure if that is something you have written yourself or something that is inside syncfusion, but that is the place to look.
The reason you have generated proxies is because you enabled (or it's enabled by default) the proxy generation of the Entity Framework DbContext.

automapper error collection was modified when multiple users are creating a user

I am receiving following error and this error only comes up when multiple users are hitting the same button. Any help/ideas will be really appreciated:
System.InvalidOperationException: Collection was modified; enumeration
operation may not execute. Generated: Wed, 10 Jun 2015 07:29:06 GMT
AutoMapper.AutoMapperMappingException:
Mapping types: User -> User ApplicationSecurityManager.Service.User ->
ApplicationSecurityManager.Models.User
Destination path: User
Source value: ApplicationSecurityManager.Service.User --->
System.InvalidOperationException: Collection was modified; enumeration
operation may not execute. at
System.Collections.Generic.List1.Enumerator.MoveNextRare() at
AutoMapper.TypeMap.<get_AfterMap>b__1(Object src, Object dest) at
AutoMapper.Mappers.TypeMapObjectMapperRegistry.PropertyMapMappingStrategy.Map(ResolutionContext
context, IMappingEngineRunner mapper) at
AutoMapper.Mappers.TypeMapMapper.Map(ResolutionContext context,
IMappingEngineRunner mapper) at
AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext
context) --- End of inner exception stack trace --- at
AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext
context) at AutoMapper.MappingEngine.Map[TDestination](Object
source, Action1 opts) at
ApplicationSecurityManager.UserManager.LoadUser(String username) at
ApplicationSecurityManager.UserManager.get_AuthenticatedUser() at
ApplicationSecurityManager.UserManager.IsAuthenticated() at
ApplicationSecurityManager.Infrastructure.ApplicationSecurityAttribute.OnAuthorization(AuthorizationContext
filterContext) at
System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext
controllerContext, IList1 filters, ActionDescriptor actionDescriptor)
at
System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback
asyncCallback, Object asyncState) at
System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult1.Begin(AsyncCallback
callback, Object state, Int32 timeout) at
System.Web.Mvc.Async.AsyncResultWrapper.Begin[TResult](AsyncCallback
callback, Object state, BeginInvokeDelegate beginDelegate,
EndInvokeDelegate1 endDelegate, Object tag, Int32 timeout) at
System.Web.Mvc.Async.AsyncResultWrapper.Begin[TResult](AsyncCallback
callback, Object state, BeginInvokeDelegate beginDelegate,
EndInvokeDelegate1 endDelegate, Object tag) at
System.Web.Mvc.Controller.<>c__DisplayClass1d.b__17(AsyncCallback
asyncCallback, Object asyncState) at
System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult1.Begin(AsyncCallback
callback, Object state, Int32 timeout) at
System.Web.Mvc.Async.AsyncResultWrapper.Begin[TResult](AsyncCallback
callback, Object state, BeginInvokeDelegate beginDelegate,
EndInvokeDelegate1 endDelegate, Object tag, Int32 timeout) at
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback,
Object state) at
System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult1.Begin(AsyncCallback
callback, Object state, Int32 timeout) at
System.Web.Mvc.Async.AsyncResultWrapper.Begin[TResult](AsyncCallback
callback, Object state, BeginInvokeDelegate beginDelegate,
EndInvokeDelegate1 endDelegate, Object tag, Int32 timeout) at
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback,
Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate
endDelegate, Object tag) at
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext,
AsyncCallback callback, Object state) at
System.Web.Mvc.MvcHandler.<>c__DisplayClass8.b__2(AsyncCallback
asyncCallback, Object asyncState) at
System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult1.Begin(AsyncCallback
callback, Object state, Int32 timeout) at
System.Web.Mvc.Async.AsyncResultWrapper.Begin[TResult](AsyncCallback
callback, Object state, BeginInvokeDelegate beginDelegate,
EndInvokeDelegate1 endDelegate, Object tag, Int32 timeout) at
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback,
Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate
endDelegate, Object tag) at
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase
httpContext, AsyncCallback callback, Object state) at
System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step,
Boolean& completedSynchronously)
This is the constructor where i think the aftermap is the problem but when debugging i don't receive the error.
Public Sub New(environmentCode As String, applicationCode As String)
MyBase.New(environmentCode, applicationCode)
SOBaseUrl = System.Configuration.ConfigurationManager.AppSettings(Enums.AppSettingKeys.SOBaseUrl.ToString())
If Not String.IsNullOrEmpty(SOBaseUrl) Then
SOBaseUrl = SOBaseUrl.TrimEnd("/")
End If
'Setup mapping.
Mapper.CreateMap(Of Service.User, Models.User)() _
.ForMember(Function(dest As Models.User) dest.ENumber, Sub(opt) opt.MapFrom(Function(src As Service.User) src.INumber)) _
.AfterMap(Sub(src As Service.User, dest As Models.User)
dest.Groups = New List(Of String)
Using service = ApplicationSecurityManager.Service.Factory.GetService()
Dim applicationPermissions = service.LoadPermissionsForUser(dest.Username, MyBase.EnvironmentCode)
If (Not applicationPermissions Is Nothing AndAlso applicationPermissions.Any(Function(x) x.Code = MyBase.ApplicationCode)) Then
dest.Groups = applicationPermissions.Single(Function(x) x.Code = MyBase.ApplicationCode).GroupNames.ToList()
End If
End Using
End Sub)
Depenendency Injection Mapping:
container.RegisterType(Of IUserManager, UserManager)(New PerThreadLifetimeManager(),
New InjectionConstructor(
ConfigurationManager.AppSettings(Common.Enums.AppSettingKeys.Environment.ToString()),
ConfigurationManager.AppSettings(Common.Enums.AppSettingKeys.ApplicationCode.ToString()))
)
In the saveUserResponse, the error is getting thrown.
Public Function Create(user As Common.Models.User, approve As Boolean) As SO.Common.Models.User Implements IUserProvider.Save
Dim saveUserResponse = UserManager.SaveUser(Mapper.Map(Of ApplicationSecurityManager.Service.User)(user))
If Not String.IsNullOrEmpty(saveUserResponse.ErrorMessage) Then
'The Security system returned an error.
Throw New Exception("Security Service returned error: " & saveUserResponse.ErrorMessage)
End If
'Return the username.
Return Mapper.Map(Of Common.Models.User)(saveUserResponse.User)
End Function
This is caused when multiple users modify the same user.Groups collection in the AfterMap() method of your mapping. To avoid this, lock the code that is processing the collection. For example:
'class level object
private object _myLock = New object()
'Setup mapping.
Mapper.CreateMap(Of Service.User, Models.User)() _
.ForMember(Function(dest As Models.User) dest.ENumber, Sub(opt) opt.MapFrom(Function(src As Service.User) src.INumber)) _
.AfterMap(Sub(src As Service.User, dest As Models.User)
SyncLock _myLock
dest.Groups = New List(Of String)
Using service = ApplicationSecurityManager.Service.Factory.GetService()
Dim applicationPermissions = service.LoadPermissionsForUser(dest.Username, MyBase.EnvironmentCode)
If (Not applicationPermissions Is Nothing AndAlso applicationPermissions.Any(Function(x) x.Code = MyBase.ApplicationCode)) Then
dest.Groups = applicationPermissions.Single(Function(x) x.Code = MyBase.ApplicationCode).GroupNames.ToList()
End If
End Using
End SyncLock
End Sub)
This is pretty common mistake modifying a collection while iterating it. Is it possible you are leaving something out here we can't see? Anyway's in the code that you have provided there is not any such scenario from what I can see. This means that you might be calling this in a multi-threaded environment and the collection is being modified in some other thread.
What can you try?
Look into locking your enumeration so only one thread at a time can be accessed. It's possible that it's being accessed multiple time's when user's are clicking on the button.
Here's a good link to help you out: http://weblogs.asp.net/leftslipper/mvc-locking-the-routecollection

Facebook app using ASP.Net MVC

I'm trying to create a Facebook app using default Facebook Template for Asp.Net MVC. I'm registered in developers.facebook.com and created an app.
I've created the ASP.NET based MVC webpage using following steps:
I've enabled the SSL property to True.
Copied the SSL URL (in my case it was localhost:44301).
In Solution Explorer, right clicked the MvcFBTestApp and select Properties.
Select the Web tab. Paste the SSL URL into the Project Url box, then click Create Virtual
Directory.
I've used the App ID/App Secret and Namespace of facebook App and configured the web.config file of my MVCApp with these settings.
Saved the project and Run the project.
Now if I run the app it request for Facebook login and logs in to facebook. But after that it generates following error instead of showing default MVC webpage. Appreciate if anyone can give me guidance.
Server Error in '/' Application.
Could not convert string to integer: public_profile. Path 'data[0].permission', line 1, position 39.
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: Newtonsoft.Json.JsonReaderException: Could not convert string to integer: public_profile. Path 'data[0].permission', line 1, position 39.
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:
[JsonReaderException: Could not convert string to integer: public_profile. Path 'data[0].permission', line 1, position 39.]
Newtonsoft.Json.JsonReader.ReadAsInt32Internal() +921
Newtonsoft.Json.JsonTextReader.ReadAsInt32() +39
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter) +228
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateDictionary(IWrappedDictionary wrappedDictionary, JsonReader reader, JsonDictionaryContract contract, JsonProperty containerProperty, String id) +1469
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue) +866
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue) +184
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateList(IWrappedCollection wrappedList, JsonReader reader, JsonArrayContract contract, JsonProperty containerProperty, String id) +1180
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateList(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, Object existingValue, String id) +698
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue) +233
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.SetPropertyValue(JsonProperty property, JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, Object target) +598
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id) +1799
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue) +517
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue) +184
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent) +740
Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType) +1143
Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType) +47
Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings) +193
Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type) +44
Facebook.FacebookClient.ProcessResponse(HttpHelper httpHelper, String responseString, Type resultType, Boolean containsEtag, IList1 batchEtags) +2070
Facebook.FacebookClient.Api(HttpMethod httpMethod, String path, Object parameters, Type resultType) +1168
Facebook.FacebookClient.Get(String path, Object parameters, Type resultType) +52
Facebook.FacebookClient.Get(String path, Object parameters) +139
Facebook.FacebookClient.Get(String path) +100
Microsoft.AspNet.Mvc.Facebook.Client.FacebookClientExtensions.GetCurrentUserPermissions(FacebookClient client) +74
Microsoft.AspNet.Mvc.Facebook.Providers.DefaultFacebookPermissionService.GetUserPermissions(String userId, String accessToken) +217
Microsoft.AspNet.Mvc.Facebook.Authorization.FacebookAuthorizeFilter.OnAuthorization(AuthorizationContext filterContext) +5182
System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList1 filters, ActionDescriptor actionDescriptor) +143
System.Web.Mvc.Async.<>c__DisplayClass25.b__1e(AsyncCallback asyncCallback, Object asyncState) +978
System.Web.Mvc.Async.WrappedAsyncResult1.Begin(AsyncCallback callback, Object state, Int32 timeout) +161
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate1 endDelegate, Object tag, Int32 timeout) +92
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate1 endDelegate, Object tag) +53
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +523
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState) +83
System.Web.Mvc.Async.WrappedAsyncResult1.Begin(AsyncCallback callback, Object state, Int32 timeout) +161
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate1 endDelegate, Object tag, Int32 timeout) +92
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag, Int32 timeout) +97
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag) +53
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +501
System.Web.Mvc.Async.WrappedAsyncResult1.Begin(AsyncCallback callback, Object state, Int32 timeout) +161
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate1 endDelegate, Object tag, Int32 timeout) +92
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag, Int32 timeout) +97
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag) +53
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +417
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +49
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState) +127
System.Web.Mvc.Async.WrappedAsyncResult1.Begin(AsyncCallback callback, Object state, Int32 timeout) +161
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +92
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag, Int32 timeout) +97
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag) +53
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +373
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +88
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +50
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Thanks & BR,
Ahmed
This a parsing problem inside the Newtonsoft.Json library. Some string can't be parsed into an integer.
Try to ensure that you are installing the latest updated version of the Newtonsoft.Json library.

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