I have a silverlight project that works perfectly when I run it independently (i.e. run instance), but when I run it from my MVC website it rises an exception that says
Unhandled Error in Silverlight 2 Application
Object reference not set to an instance of an object.
at TakingMyPicture.MainPage..ctor()
at TakingMyPicture.App.Application_Startup(Object sender, StartupEventArgs e)
at MS.Internal.CoreInvokeHandler.InvokeEventHandler(UInt32 typeIndex, Delegate handlerDelegate, Object sender, Object args)
at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName, UInt32 flags)
Related
I am trying to migrate a Team Project from TFS 2015 to Visual Studio Team Services. I connected to both the Source and Destination, selected the Team Project, mapped my users, and then when validating the Migration Summary a NullReferenceException is thrown.
The following was found in the OVSMU.log file:
2016-07-29 10:33:20,674 [1] ERROR Object reference not set to an instance of an object.
System.NullReferenceException: Object reference not set to an instance of an object.
at TFSMigrationUI.ViewModel.MigrationSummeryViewModel.worker_RunWorkerCompleted(Object sender, RunWorkerCompletedEventArgs e) in c:\Project_CheckOut\TFSMigration\TFSMigrationUI\ViewModel\MigrationSummeryViewModel.cs:line 1096
at System.ComponentModel.BackgroundWorker.OnRunWorkerCompleted(RunWorkerCompletedEventArgs e)
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)
Has anyone seen a similar problem?
We are running web site with around 15.000 realtime user (google analytics) (Around 1000 request/sec (perf counters)).
We have two web server behind load balancer.
Sometimes every day sometimes 1 time in a week one of our web servers stop execute requests and start to response with error and every request is logging following exception:
"System.IndexOutOfRangeException - Index was outside the bounds of the array."
Our environment : IIS 8.5, .Net 4.5.0, Mvc 5.1.0, Unity 3.5 (same state with 3.0), WebActivatorEx 2.0
In IIS, Worker Process 1 and other settings are with defaults.
We could not catch any specific scenario made this error. After App pool recycle everything start with no problem. And before every request respond with error, there is not any error related with it.
There is one question asked in the past with related old Unity version:
https://unity.codeplex.com/discussions/328841
http://unity.codeplex.com/workitem/11791
Could not see anything I can do about it.
Here exception details:
System.IndexOutOfRangeException
Index was outside the bounds of the array.
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at System.Collections.Generic.List`1.Enumerator.MoveNext()
at System.Linq.Enumerable.WhereListIterator`1.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at Microsoft.Practices.Unity.NamedTypesRegistry.RegisterType(Type t, String name)
at Microsoft.Practices.Unity.UnityDefaultBehaviorExtension.OnRegisterInstance(Object sender, RegisterInstanceEventArgs e)
at System.EventHandler`1.Invoke(Object sender, TEventArgs e)
at Microsoft.Practices.Unity.UnityContainer.RegisterInstance(Type t, String name, Object instance, LifetimeManager lifetime)
at Microsoft.Practices.Unity.UnityContainerExtensions.RegisterInstance[TInterface](IUnityContainer container, TInterface instance, LifetimeManager lifetimeManager)
at DemoSite.News.Portal.UI.App_Start.UnityConfig.<>c__DisplayClass1.<RegisterTypes>b__0()
at DemoSite.News.Portal.Core.Controller.BaseController.Initialize(RequestContext requestContext)
at System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Async.AsyncResultWrapper.Begin[TState](AsyncCallback callback, Object callbackState, BeginInvokeDelegate`1 beginDelegate, EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext)
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)
My configuration is as follows:
public static void RegisterTypes(IUnityContainer container)
{
var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
container.LoadConfiguration(section);
ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(container));
}
Initialize method as follow:
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
if (requestContext.RouteData.Values["ViewActionId"] != null)
{
int viewActionId;
if (!int.TryParse(requestContext.RouteData.Values["ViewActionId"].ToString(), out viewActionId))
return;
var cacheProvider = ServiceLocator.Current.GetInstance<ICacheProvider>();
List<ViewActionClass> viewActionClasses = null;
string cacheKey = CacheKeyCompute.ComputeCacheKey("ViewActionClass", CacheKeyTypes.DataCache,
new KeyValuePair<string, string>("viewActionId", viewActionId.ToString()));
_configuration = ServiceLocator.Current.GetInstance<IConfiguration>();
viewActionClasses =
cacheProvider.AddOrGetExistingWithLock<List<ViewActionClass>>(cacheKey, () =>
{
var viewActionClassBusiness =
ServiceLocator.Current.GetInstance<IViewActionClassBusiness>();
return viewActionClassBusiness.ViewActionClassGetByViewActionId(viewActionId);
});
ViewBag.ActionClass = viewActionClasses;
ViewBag.Configuration = _configuration;
}
base.Initialize(requestContext);
}
Registration xml for ICacheProvider, IConfiguration and IViewActionClassBusiness
<type type="DemoSite.Runtime.Caching.ICacheProvider, DemoSite.Core"
mapTo="DemoSite.Runtime.Caching.ObjectCacheProvider, DemoSite.Core">
<lifetime type="containerControlledLifetimeManager" />
</type>
<type type="DemoSite.Core.Configuration.IConfiguration, DemoSite.Core"
mapTo="DemoSite.Core.Configuration.ConfigFileConfiguration, DemoSite.Core">
<lifetime type="containerControlledLifetimeManager" />
</type>
<type type="DemoSite.News.Business.IViewActionClassBusiness, DemoSite.News.Business"
mapTo="DemoSite.News.Business.Default.ViewActionClassBusiness, DemoSite.News.Business.Default">
<lifetime type="perRequestLifetimeManager" />
</type>
Maybe it is related with high traffic.
Is there anyone encounter a problem like that and any solution ?
Thanks in advance
As far as I can see from the stack trace you are registering instances in the container during the web request. The RegisterType and RegisterInstance methods are not thread-safe in Unity (and this probably holds for most DI libraries in .NET). This explains why this is happening to at random points and under high load.
It is good practice to register your container only at start-up and don't change it later on. With the Dependency Inversion Principle and Dependency Injection pattern in particular you try to centralize the knowledge of how object graphs are wired, but you are decentralizing it again by doing new registrations later on. And even if registration was thread-safe with Unity, it's still very likely that you introduce race conditions by changing registrations during runtime.
UPDATE
Your code has the following code that causes the problems:
ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(container));
This seems very innocent, but in fact it causes both a concurrency bug and a memory leak.
Because the new statement is inside the lambda, it will cause a new UnityServiceLocator to be created every time you call ServiceLocator.Current. That wouldn't be bad by itself, but the UnityServiceLocator's constructor makes a call to container.RegisterInstance to register itself in the container. But as I already said: calling RegisterInstance` is not thread-safe.
But even if it was thread-safe, it still causes a memory leak in your application, since a call to RegisterInstance will not replace an existing registration, but appends it to a list of registrations. This means that the list of UnityServiceLocator instances in the container will keep growing and will eventually cause the system to crash with an OutOfMemoryException. You are actually lucky that you hit this concurrency bug first, because the OOM bug would be much harder to trace back.
The fix is actually very simple: move the construction of the UnityServiceLocator out of the lambda and return that single instance every time:
var locator = new UnityServiceLocator(container);
ServiceLocator.SetLocatorProvider(() => locator);
The behavior of the UnityServiceLocator is a design flaw in my opinion, because since RegisterInstance is not thread-safe and the UnityServiceLocator has no idea how many times it is created, it should never call RegisterInstance from within its constructor -or at least- not without doing a check whether it is safe to register that instance.
Problem however is that removing that call to RegisterInstance is a breaking change, but still probably the best solution for the Unity team. Most users will probably not notice the missing IServiceLocator registration anyway and if they do, Unity will communicate a clear exception message in that case. Another option would be to let the UnityServiceLocator check whether any instances have already been resolved from the container, and in that case throw an InvalidOperationException from within the UnityServiceLocator's constructor.
I have a fairly complex MVC Application which must initialize when the Application starts. I am trying to diagnose why the App pool is restarting after the first MVC page is rendered. To diagnose this issue, I put break points on Application_Start and Application_End. Applicaiton_Start is called as expected. At the end of the first returned HTML/Razor page from my application, Application_End is called. On the next page request, Application_Start get called again, and then seems to run as expected without restarting.
I thought this was caused by Razor compiling the views at runtime, which would then updating the BIN foldee. I know that IIS and IIS Express restart the APP pool when the BIN folder is updated, so I assumed this MVC Razor compllation was causing the IIS process to restart the app pool. To mitigate this, I followed the instructions here: https://chrismckee.co.uk/asp-net-mvc-compiled-views/ to pre-compile my Razor views. I know that the vies are now pre-compiled, as this did locate several compile issues [compile errors] that would not have been found until runtime without these configuration changes resulting in the pre-complication of the Razor views.
So the question is this:
1) How Can I diagnose why the app pool is restarting?
2) Does anyone know why this happens in and MVC application running in IISExpress?
[... and obviously, how to prevent it from happening]
Thanks
jloper
Update #2:
I looked up Browser Link and figured out quickly that it not necessary and really not being used. I turn off BrowserLink and sure enough, the exception goes away. Now the Application_Start is called as expected, Application_End is called [and no exception has occurred (System.GetLastError() returns null]. Application_Exception is NEVER called. Application_Start is called a second time.
All state of the application is reset when the Application_End is called.
Update #1:
As suggested, I added Application_Error and retrieved the last exception using Server.GetLastError(). Here is the exception that was returned:
The thread 0xc4c has exited with code 259 (0x103).
System.Web.HttpException (0x80004005): The controller for path '/__browserLink/requestData/8cf754f80e264fd392f4a0fbffea67e4' was not found or does not implement IController.
at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType)
at System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName)
at System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Also, I added the same code to Application_End. At the point that Application_End is being called, System.GetLastError() return nulls.
I found a trick somewhere on the web (forget where) that you can use reflection to get the reason in the application_end event:
Sub Application_End(sender As Object, e As EventArgs)
Dim runtime As HttpRuntime = CType(GetType(HttpRuntime).InvokeMember("_theRuntime", Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Static Or Reflection.BindingFlags.GetField, Nothing, Nothing, Nothing), HttpRuntime)
Dim shutDownMessage = CType(runtime.GetType().InvokeMember("_shutDownMessage", Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance Or Reflection.BindingFlags.GetField, Nothing, runtime, Nothing), String)
Dim shutDownStack = CType(runtime.GetType().InvokeMember("_shutDownStack", Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance Or Reflection.BindingFlags.GetField, Nothing, runtime, Nothing), String)
'Log reason
outside of adding IIS tracing, this was a code-specific way that I was able to extract the reason...
Brian Main's answer worked perfectly, showing me the message that a file changed in the project folder, which caused a restart.
For those interested, here is the C# version.
var runtime = typeof (HttpRuntime).InvokeMember("_theRuntime", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.GetField, null, null, null);
var shutDownMessage = runtime.GetType().InvokeMember("_shutDownMessage", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField, null, runtime, null);
var shutDownStack = runtime.GetType().InvokeMember("_shutDownStack", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField, null, runtime, null);
Your problem is a bug in Visual Studio's "Browser Link" feature. This was fixed in an update. Apply the latest Update (Update 4) to Visual Studio 2013 and your problem should be fixed.
I'm using Proxem wrapper for Stanford Parser and I'm facing problem with Parsing in ASP.NET MVC 3 and 4 application. It throws
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object.
at Proxem.Antelope.Parsing.Sentence.a(List`1 A_0)
at Proxem.Antelope.Parsing.Sentence..ctor(SerializationInfo info, StreamingContext ctxt)
--- End of inner exception stack trace ---
In WPF and console application it works fine.
I fixed it. Constructor Parser(string path) is invoking constructor Parser(string path, int poolsize) with poolsize value = 1. Using constructor Parser(string path, int poolsize) with values -> Parser(yourPath, 0) make it work with MVC and WCF.
I created a basic .NET 4.0 application and referenced the Saxon assemblies. Here is the list of dll's I referenced in the project.
saxon9.dll
saxon9api.dll
IKVM.OpenJDK.ClassLibrary.dll
IKVM.Runtime.dll
The code for the application is as follows:
Sub Main()
Console.WriteLine("Trying to instantiate SaxonProcessor...")
Try
Dim SaxonProcessor As Saxon.Api.Processor = New Saxon.Api.Processor()
Catch ex As Exception
Console.WriteLine("Error: " & ex.Message & ex.StackTrace)
Console.Read()
End Try
Console.WriteLine("Saxon instantiated successfully!")
Console.Read()
End Sub
When I run this application on our IIS machine, I get the following output:
Trying to instantiate SaxonProcessor...
Saxon instantiated successfully!
I then created a basic web application project and referenced the same files as the windows application. I deployed the web application to a virtual directory that contains all the referenced assemblies. I put the following code inside my Default.aspx page:
Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Response.Write("Trying to instantiate SaxonProcessor...")
Try
Dim SaxonProcessor As Saxon.Api.Processor = New Saxon.Api.Processor()
Response.Write("Saxon instantiated successfully!")
Catch ex As Exception
Response.Write("Error: " & ex.Message & ex.StackTrace)
End Try
End Sub
End Class
When I load the page, it gives me this exception:
Trying to instantiate SaxonProcessor...Error: The type initializer for 'IKVM.NativeCode.java.lang.Thread' threw an exception. at IKVM.NativeCode.java.lang.Class.forName0(String name, Boolean initialize, Object loader) at java.lang.Class.forName0(String , Boolean , ClassLoader ) at java.lang.Class.forName(String className) at net.sf.saxon.dotnet.DotNetExtensionFunctionFactory.class$(String x0) at net.sf.saxon.dotnet.DotNetExtensionFunctionFactory..ctor(Configuration config) at net.sf.saxon.dotnet.DotNetPlatform.initialize(Configuration config) at net.sf.saxon.Configuration.init() at net.sf.saxon.Configuration..ctor() at Saxon.Api.Processor..ctor() at BealSaxxon._Default.Page_Load(Object sender, EventArgs e) in C:\Users\u0147101\Desktop\BealSaxxon\BealSaxxon\Default.aspx.vb:line 9
FULL STACKTRACE FROM IIS MACHINE:
System.TypeInitializationException: The type initializer for 'IKVM.NativeCode.java.lang.Thread' threw an exception. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.TypeInitializationException: The type initializer for 'java.io.BufferedInputStream' threw an exception. ---> java.lang.RuntimeException: java.lang.IllegalAccessException: Class java.util.concurrent.atomic.AtomicReferenceFieldUpdater can not access a member of class java.io.BufferedInputStream with modifiers "volatile" ---> java.lang.IllegalAccessException: Class java.util.concurrent.atomic.AtomicReferenceFieldUpdater can not access a member of class java.io.BufferedInputStream with modifiers "volatile"
at sun.reflect.misc.ReflectUtil.ensureMemberAccess(Class currentClass, Class memberClass, Object target, Int32 modifiers)
at java.util.concurrent.atomic.AtomicReferenceFieldUpdater.AtomicReferenceFieldUpdaterImpl..ctor(Class , Class , String )
--- End of inner exception stack trace ---
at java.util.concurrent.atomic.AtomicReferenceFieldUpdater.AtomicReferenceFieldUpdaterImpl..ctor(Class , Class , String )
at java.util.concurrent.atomic.AtomicReferenceFieldUpdater.newUpdater(Class tclass, Class vclass, String fieldName)
at java.io.BufferedInputStream..cctor()
--- End of inner exception stack trace ---
at java.io.BufferedInputStream.__<clinit>()
at java.lang.System.initializeSystemClass()
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle._InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
at System.RuntimeMethodHandle.InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
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 IKVM.NativeCode.java.lang.Thread..cctor()
--- End of inner exception stack trace ---
at IKVM.NativeCode.java.lang.Class.forName0(String name, Boolean initialize, Object loader)
at java.lang.Class.forName(String className)
at net.sf.saxon.dotnet.DotNetExtensionFunctionFactory.class$(String x0)
at net.sf.saxon.dotnet.DotNetExtensionFunctionFactory..ctor(Configuration config)
at net.sf.saxon.dotnet.DotNetPlatform.initialize(Configuration config)
at net.sf.saxon.Configuration.init()
at net.sf.saxon.Configuration..ctor()
at Saxon.Api.Processor..ctor()
at EDG.Transforms..ctor()
at EDG.Main..ctor(NameValueCollection applicationSettings, List`1 exceptionList)
at EDG.EGallery..ctor(NameValueCollection ConfigurationSettings, List`1 ExceptionList)
Has anyone seen this exception before? I've searched extensively on Google but nobody seems to have had this specific exception. I'm thinking it's a permissions problem with IIS, but I don't know for sure. The application pool this application is running under is setup with a machine administrator.
I think this can be 2 types of causes.
One of the IKVM dll is missing. Add all dll of IKVM to test if this solve the problem.
IKVM is compiled for .NET 2 and not version 4. You need to add a version mapping to your app.config.
In this situation, it was a product called OpNET that was interfering with apps using the JVM. Once its services and processes were stopped, the Saxon assembly worked fine.