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
Related
After spending some hours searching for an answer, I've concluded that the question needs to be refocused on the Azure storage connection string
<add key="yadayadayada_AzureStorageConnectionString" value="DefaultEndpointsProtocol=https;AccountName=yadayada;AccountKey=yoyoyoyo==;EndpointSuffix=core.windows.net" />
and the use of ImageResizer and AzureReader2 which also has a connection string. The settings for that are:
<resizer>
<pipeline defaultCommands="autorotate.default=true" />
<plugins>
<add name="AzureReader2" connectionString="DefaultEndpointsProtocol=https;AccountName=accountname;AccountKey=acctkey==" endpoint="http://acctnumber.blob.core.windows.net/" prefix="~/azure" />
</plugins>
As I change the endpoints, I get different errors. When I change the azure prefix to "~/" it crashes.
Here is the original question, but I'm asking with more certainty what should the storage connection strings be to authorize upload to my azure website.
Here's the original question: Uploading from my development machine to Azure blob storage works fine. However, uploading from the deployed (on Azure) asp.net mvc app gets this error: System.IO.FileNotFoundException: Could not find file 'D:\Windows\system32\
Do I need to establish write permission for the app, and if so how?
Or is there something wrong with my code?
private CloudBlobContainer GetCloudBlobContainer()
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("accountidhere_AzureStorageConnectionString"));
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("FOLDER NAME HERE");
return container;
}
public async Task<ActionResult> AddAnnouncementPhotos(AddPhotosViewModel vm, FormCollection fcoll)
{
if (ModelState.IsValid)
{
int theID = vm.ThePost.PostId;
foreach (string fileName in Request.Files)
{
HttpPostedFileBase fb = Request.Files[fileName];
string caption = fileName.Replace("File", "Photo");
var phostring = caption + ".PhotoCaption";
if (fb != null && fb.ContentLength > 0 && fb.ContentType.StartsWith("image"))
{
string path = fb.FileName;
string ext = path.Substring(path.LastIndexOf("."));
string newname = Guid.NewGuid() + ext;
CloudBlobContainer container = GetCloudBlobContainer();
CloudBlockBlob blob = container.GetBlockBlobReference(newname);
blob.Properties.ContentType = fb.ContentType;
using (var fileStream = System.IO.File.OpenRead(path))
{
blob.UploadFromStream(fileStream);
}
Adding the Stack Trace:
FileNotFoundException: Could not find file 'D:\Windows\system32\DSC02724.JPG'.]
System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) +519
System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) +829
System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share) +65
swIndWorkshop.Controllers.<AddAnnouncementPhotos>d__14.MoveNext() in C:\Users\JHstandard\Documents\aspnetProjects\swIndWorkshop\swIndWorkshop\Controllers\AnnouncementsController.cs:420
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +61
System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) +97
System.Web.Mvc.Async.<>c__DisplayClass8_0.<BeginInvokeAsynchronousActionMethod>b__1(IAsyncResult asyncResult) +17
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__11_0() +50
System.Web.Mvc.Async.<>c__DisplayClass11_1.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2() +228
System.Web.Mvc.Async.<>c__DisplayClass7_0.<BeginInvokeActionMethodWithFilters>b__1(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.<>c__DisplayClass3_6.<BeginInvokeAction>b__3() +35
System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__5(IAsyncResult asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +11
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +45
System.Web.Mvc.<>c.<BeginExecute>b__151_2(IAsyncResult asyncResult, Controller controller) +13
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +28
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +577
System.Web.<>c__DisplayClass285_0.<ExecuteStepImpl>b__0() +24
System.Web.StepInvoker.Invoke(Action executionStep) +100
System.Web.<>c__DisplayClass4_0.<Invoke>b__0() +17
Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule.OnExecuteRequestStep(HttpContextBase context, Action step) +64
System.Web.<>c__DisplayClass284_0.<OnExecuteRequestStep>b__0(Action nextStepAction) +54
System.Web.StepInvoker.Invoke(Action executionStep) +84
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +100
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +163
You don't specify the whole path used in var fileStream = System.IO.File.OpenRead(path), so it's current directory by default.
On Azure the process current working directory is D:\Windows\system32\, where we have no access to write and the uploaded file can't be there either.
Update
Recommand to use InputStream, so we don't have to save file on web server.
Just replace System.IO.File.OpenRead(path) with fb.InputStream.
To use System.IO.File.OpenRead(path), need some modification in your if segment.
if (fb != null && fb.ContentLength > 0 && fb.ContentType.StartsWith("image"))
{
string path = fb.FileName;
// add these two line to save file on web app server
var wholePath = Path.Combine(Server.MapPath("~/"), path);
fb.SaveAs(wholePath);
.....
using (var fileStream = System.IO.File.OpenRead(wholePath))
{
blob.UploadFromStream(fileStream);
}
....
}
I understand what an Index Out of Range Exception is, however, I can't seem to figure out what is going on in the Stack Trace below.
This is an asp.net website, and it has been working without issue for the past few years. I have checked with the System Administrator and they noted nothing has changed on the server hosting the website or dc. Currently at a stand still, any ideas as to where to look or begin diagnosing?
[IndexOutOfRangeException: Index was outside the bounds of the array.]
System.DirectoryServices.AccountManagement.SidList.TranslateSids(String target, IntPtr[] pSids) +1507
System.DirectoryServices.AccountManagement.SidList..ctor(SID_AND_ATTR[] sidAndAttr) +142
System.DirectoryServices.AccountManagement.ADStoreCtx.GetGroupsMemberOfAZ(Principal p) +220
System.DirectoryServices.AccountManagement.UserPrincipal.GetAuthorizationGroupsHelper() +50
PayDirectory.Classes.ActiveDirectoryAdapter.IsUserAllowed(String username, IList`1 allowedgroups) in C:\Users\johndoe\Documents\Visual Studio 2010\Projects\PayDirectory\PayDirectory\Classes\ActiveDirectoryAdapter.cs:35
PayDirectory.Controllers.AccountController.CheckUser(String sessionid) in C:\Users\johndoe\Documents\Visual Studio 2010\Projects\PayDirectory\PayDirectory\Controllers\AccountController.cs:42
lambda_method(Closure , ControllerBase , Object[] ) +108
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +188
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +28
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +29
Etc.
That is the beginning of the Stack Trace, I can post the entire trace if necessary.
Basically, the application takes the session id of a user logged into Joomla, checks ad to see if that user is in a particular group (Principals) and allows them to view certain content, otherwise it will state Access is Denied.
EDIT
Adding source code for "IsuserAllowed" in ActiveDirectoryAdapter class
public Boolean IsUserAllowed(string username, IList<string> allowedgroups)
{
PrincipalContext domain = new PrincipalContext(ContextType.Domain, "Redmond");
UserPrincipal user = UserPrincipal.FindByIdentity(domain, username);
List<GroupPrincipal> groups = new List<GroupPrincipal>();
if (user != null)
{
PrincipalSearchResult<Principal> authGroups = user.GetAuthorizationGroups();
foreach (Principal p in authGroups)
{
if (p is GroupPrincipal)
{
groups.Add((GroupPrincipal)p);
}
}
}
string groupstring = string.Join(",", (object[])groups.ToArray());
string[] groupnames = groupstring.Split(',');
for (int i = 0; i < allowedgroups.Count; i++)
{
if (groupnames.Contains(allowedgroups[i]))
{
return true;
}
}
return false;
}
I get error Unsupported Operation. A document processed by the JRC engine cannot be opened in the C++ stack when trying to programmatically display a Crystal Report developed in the Crystal Reports environment.
I am using MS Visual Studio 2012 and trying to I have posted the entire code I am using for calling this report below, as well as the stack trace. The problem is occuring in my VS development environment. I have seen several posts and solutions for this when it occurs after publishing the application. I am very new to Crystal Reports, and I am unable to find a way to make this work. The is occurring at the load point.
Thanks for any help
rpt properties
Build Action: Content
Cope to Output Directory: Do not copy
Custom Tool: blank
Custom Tool Name: blank
Imports CrystalDecisions.CrystalReports.Engine
Public Class CrystalReportsController
Inherits System.Web.Mvc.Controller
Public Function EmployeeQuoteLanscape() As ActionResult
Dim rptH As New ReportClass()
rptH.FileName = Server.MapPath("~/Content/Reprots/Quote/EmployeeQuoteLandscape.rpt")
rptH.Load()
rptH.SetDataSource("")
Dim stream As IO.Stream = rptH.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat)
Return File(stream, "application/pdf")
End Function
End Class
Server Error in '/' Application.
Unsupported Operation. A document processed by the JRC engine cannot be opened in the C++ stack.
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.Runtime.InteropServices.COMException: Unsupported Operation. A document processed by the JRC engine cannot be opened in the C++ stack.
Source Error:
Line 6: Dim rptH As New ReportClass()
Line 7: rptH.FileName = Server.MapPath("~/Content/Reprots/Quote/EmployeeQuoteLandscape.rpt")
Line 8: rptH.Load()
Line 9: rptH.SetDataSource("")
Line 10: Dim stream As IO.Stream = rptH.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat)
Source File: D:\Visual Studio Projects\GBIP\gbip_new\gbip_new\Controllers\CrystalReportsController.vb Line: 8
Stack Trace:
[COMException (0x80041811): Unsupported Operation. A document processed by the JRC engine cannot be opened in the C++ stack.]
CrystalDecisions.ReportAppServer.ClientDoc.ReportClientDocumentClass.Open(Object& DocumentPath, Int32 Options) +0
CrystalDecisions.ReportAppServer.ReportClientDocumentWrapper.Open(Object& DocumentPath, Int32 Options) +138
CrystalDecisions.ReportAppServer.ReportClientDocumentWrapper.EnsureDocumentIsOpened() +546
[CrystalReportsException: Load report failed.]
CrystalDecisions.ReportAppServer.ReportClientDocumentWrapper.EnsureDocumentIsOpened() +647
CrystalDecisions.CrystalReports.Engine.ReportDocument.Load(String filename, OpenReportMethod openMethod, Int16 parentJob) +1799
CrystalDecisions.CrystalReports.Engine.ReportClass.Load(String reportName, OpenReportMethod openMethod, Int16 parentJob) +278
CrystalDecisions.CrystalReports.Engine.ReportClass.Load() +38
gbip_new.CrystalReportsController.EmployeeQuoteLanscape() in D:\Visual Studio Projects\GBIP\gbip_new\gbip_new\Controllers\CrystalReportsController.vb:8
lambda_method(Closure , ControllerBase , Object[] ) +102
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +59
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +435
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +60
System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeSynchronousActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +50
System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +75
System.Web.Mvc.Async.<>c__DisplayClass81.b__7(IAsyncResult ) +44
System.Web.Mvc.Async.WrappedAsyncResult1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +49
System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +126
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +323
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +44
System.Web.Mvc.Async.WrappedAsyncResult1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +50
System.Web.Mvc.Async.<>c_DisplayClass2a.b_20() +68
System.Web.Mvc.Async.<>c_DisplayClass25.b_22(IAsyncResult asyncResult) +184
System.Web.Mvc.Async.WrappedAsyncResult1.End() +136
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +40
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +47
System.Web.Mvc.Async.WrappedAsyncResult1.End() +151
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
System.Web.Mvc.Async.<>c_DisplayClass4.b__3(IAsyncResult ar) +47
System.Web.Mvc.Async.WrappedAsyncResult1.End() +151
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +45
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +47
System.Web.Mvc.Async.WrappedAsyncResult1.End() +151
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9629296
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18034
The word "Reports" is misspelled in your filepath. Perhaps that's the problem?
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);
}
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.