Download large file without buffering - asp.net-mvc

I am getting an OutOfMemoryException attempting to download a large file from an MVC controller. I want to reduce demand on server memory, so how can I download a file without first buffering its entire contents?
My code is:
var cd = new System.Net.Mime.ContentDisposition
{
FileName = filename,
Inline = false
};
Response.AppendHeader("Content-Disposition", cd.ToString());
var stream = new MemoryStream();
ExportService service = new ExportService(_mapper, Repository);
service.ExportVersion(view.ExportType, version, products, regions,
indicators, periods, stream);
stream.Position = 0;
return File(stream, "text/plain");
I would like the content to be streamed to the browser as I am creating it. To try to acheive that, I passed Response.OutputStream to the service and wrote to that instead of to the MemoryStream. However, that creates the same OutOfMemoryException, since by default, ASP.NET buffers all content before sending it to the browser. Even if I set Response.BufferOutput = false (and return an EmptyResult) I still get an OutOfMemoryException.
Response.BufferOutput = false;
ExportService service = new ExportService(_mapper, Repository);
service.ExportVersion(view.ExportType, version, products, regions,
indicators, periods, Response.OutputStream);
return new EmptyResult();
Update
I am confident that this problem is due to hitting the limit of available memory since the code works on one machine, but not on another. Furthermore, on the machine with the more restricted memory, the strack trace shows the error occurs at variable locations in the code, depending on the content being downloaded. Here is a sample stack trace which shows the exception occurring while allocating memory to a List object:
[OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.]
System.Collections.Generic.List`1.set_Capacity(Int32 value) +62
System.Collections.Generic.List`1.EnsureCapacity(Int32 min) +43
System.Collections.Generic.List`1.Add(T item) +51
MyApp.Mapping.DocumentVersionEntityConverter.LoadMultiVariableData(DocumentVersion version, MultiVariableQuestionView view) in c:\svn\Client Applications\MyApp\Web\Config\Mapping\DocumentVersionEntityConverter.cs:207
MyApp.Mapping.DocumentVersionEntityConverter.SetResponses(DocumentVersion version, List`1 questions, DataFilters filters) in c:\svn\Client Applications\MyApp\Web\Config\Mapping\DocumentVersionEntityConverter.cs:112
MyApp.Mapping.DocumentVersionEntityConverter.ScanSection(DocumentVersion version, SectionView section, DataFilters filters) in c:\svn\Client Applications\MyApp\Web\Config\Mapping\DocumentVersionEntityConverter.cs:79
MyApp.Mapping.DocumentVersionEntityConverter.Convert(ResolutionContext context) in c:\svn\Client Applications\MyApp\Web\Config\Mapping\DocumentVersionEntityConverter.cs:63
AutoMapper.DeferredInstantiatedConverter`2.Convert(ResolutionContext context) +57
AutoMapper.<>c__DisplayClass15.<ConvertUsing>b__14(ResolutionContext context) +10
AutoMapper.Mappers.CustomMapperStrategy.Map(ResolutionContext context, IMappingEngineRunner mapper) +13
AutoMapper.Mappers.TypeMapMapper.Map(ResolutionContext context, IMappingEngineRunner mapper) +130
AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext context) +355

Related

Azure Durable Functions Large Message Support Issue

I am having an issue returning a large list of objects from an activity function to an orchestrator function.
I have a function that downloads a 180 MB file and parses it. This file will produce a list of objects with over 962K entries. Each object has about 70 properties but only about 20% of them are populated.
When I run the function, the code successfully downloads and parses the file into the list, but when the list is returned, an exception is raised with the following information:
Exception: "Exception while executing function: #######"
- Source: "System.Private.CoreLib"
Inner exception: "Error while handling parameter $return after function returned."
- Source: "Microsoft.Azure.WebJobs.Host"
Inner / Inner exception: "Exception of type 'System.OutOfMemoryException' was thrown."
- Source: "System.Private.CoreLib"
The last nested exception lists the NewtonsoftJson package as being the one making the call that generates the out of memory error being reported. I am including the full stack trace for this exception at the end.
I understand that I could possibly serialize the list of objects and store them in an Azure blob entry and then just pick it up again in the next function that needs to process it, but I thought the idea behind durable functions was to avoid all this and maintain a leaner workflow? Also, I based the design on the "Large Message Support #26" github post that states that the durable functions extensions would automatically store the function payload in a blob if the size exceeds the queue message limit (see: https://github.com/Azure/azure-functions-durable-extension/issues/26).
Is there anything I need to do to get this working?
The code is pretty simple:
[FunctionName("GetDataFromSource")]
public static IEnumerable<DataDetail> GetDataFromSource([ActivityTrigger]ISource source, ILogger logger)
{
try
{
string importSettings = Environment.GetEnvironmentVariable(source.SettingsKey);
if (string.IsNullOrWhiteSpace(importSettings))
{
logger.LogError($"No settings key information found for the {source.SourceId} data source"); }
else
{
List<DataDetail> _Data = source.GetVinData().Distinct().ToList();
return vinData;
}
}
catch (Exception ex)
{
logger.LogCritical($"Error processing the {source.SourceId} Vin data source. *** Exception: {ex}");
}
return new List<DataDetail>();
}
This is the stack trace for the most inner exception:
at System.Text.StringBuilder.ExpandByABlock(Int32 minBlockCharCount)
at System.Text.StringBuilder.Append(Char value, Int32 repeatCount)
at System.Text.StringBuilder.Append(Char value)
at System.IO.StringWriter.Write(Char value)
at Newtonsoft.Json.JsonTextWriter.WritePropertyName(String name, Boolean escape)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)
at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)
at DurableTask.Core.Serializing.JsonDataConverter.Serialize(Object value, Boolean formatted)
at Microsoft.Azure.WebJobs.Extensions.DurableTask.MessagePayloadDataConverter.Serialize(Object value, Int32 maxSizeInKB) in C:\projects\azure-functions-durable-extension\src\WebJobs.Extensions.DurableTask\MessagePayloadDataConverter.cs:line 55
at Microsoft.Azure.WebJobs.Extensions.DurableTask.MessagePayloadDataConverter.Serialize(Object value) in C:\projects\azure-functions-durable-extension\src\WebJobs.Extensions.DurableTask\MessagePayloadDataConverter.cs:line 43
at Microsoft.Azure.WebJobs.DurableActivityContext.SetOutput(Object output) in C:\projects\azure-functions-durable-extension\src\WebJobs.Extensions.DurableTask\DurableActivityContext.cs:line 136
at Microsoft.Azure.WebJobs.Extensions.DurableTask.ActivityTriggerAttributeBindingProvider.ActivityTriggerBinding.ActivityTriggerReturnValueBinder.SetValueAsync(Object value, CancellationToken cancellationToken) in C:\projects\azure-functions-durable-extension\src\WebJobs.Extensions.DurableTask\Bindings\ActivityTriggerAttributeBindingProvider.cs:line 213
at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ParameterHelper.ProcessOutputParameters(CancellationToken cancellationToken) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs:line 972
I came across a similar issue when working with Durable Functions.
There are a couple of solutions / workarounds to this:
As you say, you could store the function payload in blob storage and retrieve them when you require. This works but there is a performance hit and can take a while to retrieve depending on how big your file is.
The other option would be to batch your calls. I'm not entirely sure what your GetVinData() method does but you could modify this so you only retrieve 50,000 (or x number) items at a time. Your orchestrator could call your activity function multiple times and build up your list in the orchestrator.
[FunctionName(nameof(OrchestratorAsync))]
public async Task OrchestratorAsync([OrchestrationTrigger] IDurableOrchestrationContext context)
{
var dataDetailList = new List<DataDetail>();
var batches = BuildBatchesHere();
foreach (var batch in batches)
{
dataDetailList.AddRange(
await context.CallActivityAsync<List<DataDetail>>(
nameof(GetDataFromSource), batch);
}
// Do whatever you need with dataDetailList
}
The Durable Functions extension will automatically take care of storing large messages in blobs when they don't fit in queues and tables. However, this support assumes that enough memory is available to serialize the payloads so that they can be uploaded to blob. Unfortunately, the design of the Durable Task Framework requires serializing the payload into a string first before uploading to blob, which means there will be a lot of memory pressure.
There are a few things you can try to mitigate this problem:
Make sure your function app is running in 64-bit mode. By default, Function apps are created in 32-bit mode, which has lower memory limits. We've seen several cases where simply switching to 64-bit resolves out-of-memory issues.
Try increasing the memory limit for your particular plan. If you're running in the Azure Functions Consumption plan, maximum memory is fixed. However, if you're running in Elastic Premium or App Service Plans, you have the option of using larger VMs with more memory.
As #stephyness suggested, consider limiting the amount of data your return from your function. This could be returning a subset of the full list or it could be the full list but with smaller payloads (for example, source.GetVinData().Distinct().Select(x => x.VinNumber) (you might even get better results by simply removing .ToList(), which may be creating an unnecessary copy of your data). Essentially, return only the data that the orchestrator absolutely needs to make progress. Returning data the orchestrator doesn't need is unnecessary overhead.
Also be aware that there's a non-trivial performance impact when large message support is used. If you can avoid relying on it, your orchestrations will run much faster.
Other tips for controlling memory usage can be found in the Performance and Scale documentation.

ASP.NET: Exception when accessing the request InputStream

In my ASP.NET MVC 5 application I'm trying to access the Request.InputStream property but I get the following exception:
System.NullReferenceException: Object reference not set to an instance of an object.
at Telerik.Web.UI.Upload.RequestParser.MergeArrays(Byte[] array1, Byte[] array2)
at Telerik.Web.UI.Upload.RequestParser.get_FirstBoundary()
at Telerik.Web.UI.Upload.RequestParser..ctor(Byte[] boundary, Encoding encoding, RequestStateStore requestStateStore)
at Telerik.Web.UI.Upload.ProgressWorkerRequest.get_Parser()
at Telerik.Web.UI.Upload.ProgressWorkerRequest.UpdateProgress(Byte[] buffer, Int32 validBytes
at Telerik.Web.UI.Upload.ProgressWorkerRequest.GetPreloadedEntityBody()
at System.Web.HttpRequest.GetEntireRawContent()
at System.Web.HttpRequest.get_InputStream()
As you can see, the exception is thrown by a Telerik component. I'm indeed using Telerik web controls in my project but none of them are related to this controller. The exception occurs even if I generate a request using a tool. Looks to me like Telerik somehow injected this ProgressWorkerRequest object into my HttpRequest.
Any clues on how to get rid of it?
It doesn't have to be related to your controller. It is related to the process that the Telerik uploader is conducting and is not something to "get rid of". Basically, it is telling you that the Telerik uploader process didn't complete because it didn't find what it was expecting to.
Since Telerik controls are generally straightforward to use, you should only need something like this to get the input stream for your file:
public ActionResult UploadFile(IEnumerable<HttpPostedFileBase> fileUploader)
{
if (Request.Files.Count == 1)
{
string fileName = Request.Files[0].FileName;
Stream s = Request.Files[0].InputStream;
int size = Request.Files[0].ContentLength;
byte[] myFile = new byte[length];
s.Read(myFile, 0, size);
// Now, myFile should have the file, in bytes
}
}
If you are not getting the file, I would ensure the application has the permissions via the account it is acting under (either yours, or a service account, if a web application) to the resource you are pointing at.

Unity and Random "Index was outside the bounds of the array" exception

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.

Why does IIS Express Restart my App Pool in MVC Application

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.

if you have a DLL creating a bitmap in memory, how to return it to the browser?

I have a DLL that is going to return an object(bitmap) and I have to pass it to the browser.
All in memory, no disk access.
I know how to do it with asp.net webform but I have no clue with MVC.
with webform,
since I have control over the dll, I inherit the class with the webcontrol.image.
in the aspx page I create a simple img link like:
<img src="Handler1.ashx>
in the Handler1.ashx I have code like:
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Response.Clear()
Dim bmp As Bitmap = Nothing
Dim dll As New myDll.Class
dll.drawPicture(bmp)
context.Response.ContentType = "image/jpeg"
bmp.Save(context.Response.OutputStream, ImageFormat.Jpeg)
context.Response.End()
End Sub
(I removed the cleaning stuff/useless code to keep it short)
edit
solution is
Function img() As FileResult
Dim bmp As Bitmap = Nothing
Dim dll As New myDll.myClass
dll.DrawPicture(bmp)
Dim imgStream As New IO.MemoryStream
bmp.Save(imgStream, ImageFormat.Png)
imgStream.Position = 0
bmp.Dispose()
dll.Dispose()
bmp = Nothing
dll = Nothing
Return File(imgStream.ToArray, "image/png")
End Function
I have no problem running cleaning code on everything except the memorystream, is there a chance for a memoryleak there? (I think yes)
Use controller action which returns FileResult with Controller.File() method.
Use a generic handler and save the bitmap (.Save) with Response.OutputStream

Resources