Does EF 4 Code First's ContextBuilder Dispose its SqlConnection? - entity-framework-4

Looking at Code First in ADO.Net EF 4 CTP 3 and wondered how the SqlConnection in their walkthrough is disposed. Is that the responsibility of ContextBuilder? Is it missing from the example?
var connection = new SqlConnection(DB_CONN);
var builder = new ContextBuilder<BloggingModel>();
var connection = new SqlConnection(DB_CONN);
using (var ctx = builder.Create(connection))
{
//...
}

I just realized that I can add an event handler to ObjectContext.Disposing and resolve this.
In CTP 3 at least, Connection is not disposed when the ObjectContext is disposed.
Since I'm subclassing ObjectContext already, I implemented IDisposable in my subclass and call Connection.Dispose() from there.

Close and Dispose in SqlConnection are functionally equivalent. Therefore, as long as the connection is closed -- and I think you'll find that it is, but don't take my word for it -- the sample code works.
But since you asked, you should probably dispose of it anyway. It will do no harm, and will stop others from asking the same question.

Related

Stress Testing - EntityFramework issue - DBContext Creation

I am doing stress testing for web api (webapi2) with 20 users on boarding in 0 seconds. I am getting the following errors.
System.Data.Entity.Core.EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details. ---> System.InvalidOperationException: Invalid operation. The connection is closed.
Another error
System.Data.Entity.Core.EntityException: The underlying provider failed on Open. ---> System.InvalidOperationException: The connection was not closed. The connection's current state is connecting.
My code to get the DBContext, each time a new DBContext is getting created:
public static ForcesChecker_Context GetDataContext()
{
return new ForcesChecker_Context();
}
For one web api request this code is getting executed multiple times and multiple instances of this object is getting created. When I call 20 users at a time, it generates 20* ~10 = ~200 objects are created.
My connection string:
Min Pool Size=1;Max Pool Size=200;
It seems there is a race condition.
What settings would help to allow more users to access my system concurrently?
I fixed it. The reason was, Connection Leak. There are other places in the application wherein the DBContext object wasn't disposed properly. Particularly in UnitOfWork class, DBContext object is used, but not disposed inside the Dispose() method. That led to the connection leak. Subsequently, that led to the race condition when new threads (http requests) try to use a connection from the connection pool. Here is the solution code.
public class UnitOfWork: IDisposable, IUnitOfWork
{
ForcesChecker_Context forcesContext; //EntityFramework DBContext
...
public void Dispose()
{
forcesContext.Dispose(); //Leak prevented by this new line.
}
...
}
Thumb rule is, always remember to use Transient Life Time for the DBContext. That is a new instance every time, and dispose them immediately after use.

Band SDK doesnt seem to work from anywhere but codebehind

Universal App with MVVMLight.
So I started wondering why all the SDK examples were done from code behind rather than using a solid Wrapper class.
So I wanted to write a reusable wrapper class. No luck. Even tried adding that wrapper to a ViewModel, still no luck.
Works fine from MainView.xaml.cs
IBandInfo[] pairedBands = BandClientManager.Instance.GetBandsAsync().Result;
if (pairedBands.Length > 0)
{
using (IBandClient bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]))
{
}
}
The moment I move to any kind of OOP or View Model, ConnectAsync will never return or throw exception. I have tried this 20 different ways, is the SDK broken? What Is happening? No message, no throw, just never returns.
If I throw in Code behind, wallah it works just fine and returns the client in 1/2 second.
I have spend 5-6 hours so far on this. I wanted to create a solid wrapper class for the SDK so I could call easy calls from Model and do things like StartListener(MicrosoftBandSensor sensorToActivate).
Any suggestions?
-- For Phil's comment
I was trying to create backing variables for both client and bandinfo which would be held in a class that the VM uses. I wrote my class as IDisposable so I could dispose of both when I was done with my wrapper. I may be using this wrong to be honest.
MicrosoftBand.MicrosoftBandClient = BandClientManager.Instance.ConnectAsync(pairedBands[0]).Result;
Is what I wanted to call making it a sync call since I wanted to make the calls to bandinfo and client in the constructor then hold both until the class was destroyed and just recall the vars when needed.
My VM has :
public BandInformation MicrosoftBand
{
get { return _microsoftBand; }
set { Set(() => MicrosoftBand, ref _microsoftBand, value); }
}
If they didn't pass the bandclient in the constructor I would use:
private async Task InitBand(IBandInfo bandInfo)
{
if (bandInfo == null)
{
var allBands = await BandClientManager.Instance.GetBandsAsync();
if (allBands.Length > 0)
{
bandInfo = allBands[0];
}
}
var bandClient = await BandClientManager.Instance.ConnectAsync(bandInfo);
MicrosoftBandInfo = bandInfo;
MicrosoftBandClient = bandClient;
if (MicrosoftBandClient == null)
{
AddErrorMessage("This sample app requires a Microsoft Band paired to your device.Also make sure that you have the latest firmware installed on your Band, as provided by the latest Microsoft Health app.");
}
}
This seems fine working with BandInfo. I get back a solid seeming to work object For the client I get "thread exited" and nothing else.
Note: I had it in a try catch throwaway version at one point and nothing threw n exception either.
I assume you can do this like you would any other IDisposable where you handle the disposing yourself.
I can reinstantiate the BandClient each time, just figured I needed to detach the events at some point, meaning I had to keep ahold of the bandclient. I could keep it until done and would add and remove events as I needed each time.
It's likely your blocking call to .Result within your VM constructor is what was causing the hang. IBandClientManager.ConnectAsync() may implicitly display UI (a Windows Runtime dialog asking the user to confirm that she wants to use that specific Bluetooth device). If you've blocked the UI thread when it attempts to display UI, you've now gotten yourself into a deadlock.
Calling Task.Result is almost never a good idea, much less doing so within a constructor where you have little idea on which thread the constructor is executing. If you're working with an async API (such as the Band SDK) then your best bet is to keep that interaction async as well. Instead, defer calling ConnectAsync() until you actually need to, and do so from an async method in your VM. (Deferring the connection is a good idea anyway because you want to minimize the time connected to the Band to preserve battery life.) Then call Dispose() as early as possible to close the Bluetooth connection.
So I went and looked at a bunch of examples. Finally I landed on the GravityHeroUAP demo on the MSDN site. https://msdn.microsoft.com/en-us/magazine/mt573717.aspx?f=255&MSPPError=-2147217396
I looked at his code and the source: https://github.com/kevinash/GravityHeroUWP
He was essentially doing what I wanted to do.
However, I noticed something Bizarre. In his viewmodel everything was static!
public static IBandInfo SelectedBand
{
get { return BandModel._selectedBand; }
set { BandModel._selectedBand = value; }
}
private static IBandClient _bandClient;
public static IBandClient BandClient
{
get { return _bandClient; }
set
{
_bandClient = value;
}
}
I ended up copying this pattern (though had to throw away my favorite MVVM lib in the process, though I am sure I can get it back).
My common pattern in my VM's:
public string ExceptionOnStart {
get { return _exceptionOnStart; }
set { Set(() => ExceptionOnStart, ref _exceptionOnStart, value); }
}
It seems to be working now!
That and I got data way too fast for the
await Windows.Storage.FileIO.AppendLinesAsync(dataFile, new List<string> { toWrite });
Thank you for the help Phil, it got me looking in the right direction!
Thank you very, very much. Spent WAY to long on this. Mark

Do I really need to dispose IUnityContainer on shutdown of application

I'm maintaining code for a web application built using Asp.NET MVC. An MVC dependency resolver has been implemented using Unity container. Here's the cleanup code that's called on application shutdown.
public static void Shutdown()
{
IUnityContainer container = UnityConfig.GetConfiguredContainer();
container.Dispose(); //currently when called causes stack overflow
}
The issue we're having is that during a shutdown the call to dispose (above) causes a stack overflow exception and then the process crashes because of it. This also occurs during development when debugging the app and making changes to web.config (since changes to web.config seems to restart the application) which also stops the debugging session which normally shouldn't end. No stack overflow seems to occur if I remove the call to dispose, and the application then exits or restarts normally without the process crashing during debugging sessions.
I'm thinking of simply permanently removing the call to Dispose but I'm uncertain of the consequences, wouldn't an application shut down inevitably lead to the disposing of the container anyway?
If removing the call to dispose is not recommended then the only option would be to find the real cause which I believe lie in a circular dependency within the container itself, but I can't find it, how should I debug this issue ?
The cause of the stackoverflow is infinite recursive call to Dispose of UnityContainer, which I think is (weirdly) caused by the automatically registered IUnityContainer which is not managed by our code and should be handled in unity library. I was able to stop the infinite recursion simply by swapping out the usage of the UnityContainer class with a derived class that override Dispose and returns on a recursive call:
public class CustomUnityContainer : UnityContainer
{
private bool inDispose = false;
protected override void Dispose(bool disposing)
{
if (inDispose) //prevents recursive calls into Dispose
return;
inDispose = true;
base.Dispose(disposing);
inDispose = false;
}
}

StructureMap 2.6+ Controlling Dispose Order

I am new to StructureMap and am using it to construct an app that uses clrzmq, which is a .NET implementation of ZeroMQ.
ZeroMQ apps work by creating a single context instance and, from that instance, creating one or more ZMQ sockets to send stuff around.
In order to cleanly shut down a clrzmq app, you need to first close and Dispose any connected ZMQ sockets created from the ZMQ context, and then, only after that is done, you Dispose the ZMQ context.
If you attempt to Dispose the context prior to closing & Disposing one or more of the sockets created from that context, the Dispose call on the context will hang and your app will not exit.
So, I am looking for a way to ensure that this Dispose order is obeyed by the StructureMap containers in this app.
I've tried a registry class with wiring like so:
For< ZeroMQ.ZmqContext >().Singleton();
Profile( "SomeProfile", p =>
{
// ZmqContext instances are created with a
// custom factory method
p.For< ZeroMQ.ZmqContext >()
.Use( ZeroMQ.ZmqContext.Create() );
p.For< ISender >()
.Use< MyConcreteZmqSender >();
});
...in the above, "MyConcreteZmqSender" is a class that creates a ZMQ socket using the ZMQ context instance it receives in its constructor (the only constructor argument). It implements IDisposable, where the Dispose() implementation closes the created socket and calls Dispose() on it.
I also have a test case written to test out the Dispose behavior that looks like so:
[Test]
public void TestZmqSender()
{
ObjectFactory.Initialize( x =>
{
x.AddRegistry<MyZmqRegistry>();
} );
ObjectFactory.Profile = "SomeProfile";
ISender sender = ObjectFactory.Container.GetNestedContainer().GetInstance<ISender>();
sender.doAllTheThings();
ObjectFactory.Container.GetNestedContainer().Dispose();
ObjectFactory.Container.Dispose();
}
...in the above I tried using the nested container to get the Zmq sender instance, thinking that if I retrieve it that way, then if I later call Dispose on the nested cotainer, it will call Dispose on my socket sender before the ZMQ context gets disposed, which I assumed would happen when I called Dispose on the main parent container.
Alas, this does not appear to be what is happening, and this test case never completes. I have verified that the sender is getting properly constructed with a reference to the singleton ZMQ context. And, of course, if I manually call sender.Dispose() prior to disposing the main container, the test case completes successfully.
My first attempt didn't use the nested container at all, and it also hangs in the same way.
Anybody have any recommendations for how I can get this done without having to get a handle to all the sender instances and manually calling Dispose() on them and ensure that this is done prior to calling Dispose() on the main container?

How do I clean up in Dispose if I can't call UIKit from another thread?

Most of my UIKit Dispose overrides do something with other views before they get destroyed:
protected override void Dispose (bool disposing)
{
if (ScrollView != null) {
ScrollView.RemoveObserver (this, new NSString ("contentOffset"));
ScrollView.RemoveObserver (this, new NSString ("contentInset"));
ScrollView = null;
}
base.Dispose (disposing);
}
I just recently realized that Dispose will run on finalizer thread if disposing is false.
In this case ScrollView.RemoveObserver will be called from non-UI thread which is Bad.
What's the safe way to do UIKit-related cleanup in Dispose?
If disposing is false, then you would probably be better off not calling that code.
protected override void Dispose (bool disposing)
{
if (disposing)
{
if (ScrollView != null) {
ScrollView.RemoveObserver (this, new NSString ("contentOffset"));
ScrollView.RemoveObserver (this, new NSString ("contentInset"));
ScrollView = null;
}
}
base.Dispose (disposing);
}
As a more general answer to your question - assuming this code is in a UIViewController - it might be better to attach/detach these observers inside ViewDidAppear, ViewDidDisappear - then you can avoid this issue altogether.
Adam Kemp posted a great explanation in a mirror thread on Xamarin forums.
Only if disposing is true should you do any of that work. If it's
false then you're being called from a finalizer and so it's not safe
to access that other object. The only things you should access in that
case would be any unmanaged resources (like an IntPtr which stores a
native allocation you need to free or a native thread you need to
kill).
This obviously brings up the question of when to do the work you're
currently doing there. If you're in a view controller then you could
use a method like WillDisappear. If you are in a view then you could
just use WillMoveToWindow (which gets called with null as the window
if you are being removed from the window).
Another important bit regarding ReleaseDesignerOutlets:
You can't call ReleaseDesignerOutlets when called from a finalizer
either. Remember, it is not safe to look at any other managed objects
referenced by your object in your finalizer. Those objects may no
longer exist.
This is safe to skip because each of those other objects already has a
similar finalizer. If you never get around to calling Dispose() on
them then they will have their finalizers called from the finalizer
thread, and in that case their own finalizer will call their own
Dispose(bool) with a false, which means "you're being called from a
finalizer". Since the native object is an unmanaged resource (just an
IntPtr) it is safe for their Dispose(bool) method to release the
reference to those native resources to allow those native objects to
leave memory.
You can actually use the assembly browser to look at what NSObject's
Finalize and Dispose(bool) methods do to verify what I just described.
Whatever you do, never access your managed resources from within a
finalizer, which means never access them from Dispose(bool) when the
disposing argument is false.
Thanks Adam!
Could you use
InvokeOnMainThread(delegate {....})
to kill the UIKit stuff? Not 100% sure it'd do what you want, but thats the normal way of doing UIKit stuff when you might be on / are on a different thread.

Resources