System.AccessViolationException unknown module - c#

I currently have a controller in my WebAPI that is returning a list of some items in my database:
As below:
public ICollection<TherapyGroup> OffUnit()
{
return _context.TherapyGroups.OrderBy(g => g.Name)
.Where(x => x.GroupTypeOffUnitOnUnit == TherapyGroup.OffUnit)
.ToList();
}
Everything works fine when I am testing against my local database; however, when I switch out the database string for a remote database it throws a System.AccessViolationException. Based upon breakpoints, the data is being returned from the database fine, and it seems the problem is happening when the method returns to the WebApi in MVC. This has become a very frustrating issue, and I would love any help to navigate it.
The error window that is popping up:

Decorate the methods you want to catch these exceptions in with the HandleProcessCorruptedStateExceptions attribute. See https://msdn.microsoft.com/en-us/magazine/dd419661.aspx#id0070035 for details.
[HandleProcessCorruptedStateExceptions]
[SecurityCritical]
public ICollection<TherapyGroup> OffUnit()
{
try
{
return _context.TherapyGroups.OrderBy(g => g.Name).Where(x => x.GroupTypeOffUnitOnUnit == TherapyGroup.OffUnit).ToList();
}
catch (Exception e)
{
// set break point to see the stack trace.
Debug.WriteLine(e.InnnerException);
return null;
}
}

Related

My custom DbExecutionStrategy is not being called

My original problem was that I was experiencing deadlocks often when updating my SQL database. Through a little bit of research, I found that I'm able to define a custom DbConfiguration and with it a DbExecutionStrategy which instructs Entity Framework to automatically retry after getting certain errors after x milliseconds and y number of times. Great!
So, following the guide at https://msdn.microsoft.com/en-us/data/jj680699, I build my custom DbConfiguration, which is being used, but the associated DbExecutionStrategy seems to be ignored.
Originally, my entire DbConfiguration was being ignored, but I found that was because I was referencing it in my app.config as well as decorating my entity constructor with the DbConfigurationType attribute [DbConfigurationType(typeof(MyConfiguration))]. Now that I'm only using the app.config, at least my custom configuration is being called.
In its simplest form, my custom config looks like this:
public class MyConfiguration : DbConfiguration
{
public MyConfiguration()
{
System.Windows.MessageBox.Show("Hey! Here I am!"); //I threw this in just to check that I was calling the constructor. Simple breakpoints don't seem to work here.
SetExecutionStrategy("System.Data.SqlClient", () => new MyExecutionStrategy(3, TimeSpan.FromMilliseconds(500)));
}
}
My custom DbConfiguration is referenced in my app.config like so:
<entityFramework codeConfigurationType="MyDataLayer.MyConfiguration, MyDataLayer">
...
</entityFramework>
My custom DbExecutionStrategy is built like so:
private class MyExecutionStrategy : DbExecutionStrategy
{
public MyExecutionStrategy() : this(3, TimeSpan.FromSeconds(2))
{
System.Windows.MessageBox.Show($"MyExecutionStrategy instantiated through default constructor.");
}
public MyExecutionStrategy(int maxRetryCount, TimeSpan maxDelay) : base(maxRetryCount, maxDelay)
{
System.Windows.MessageBox.Show($"MyExecutionStrategy instantiated through parametered constructor.");
}
protected override bool ShouldRetryOn(Exception ex)
{
System.Windows.MessageBox.Show($"Overriding ShouldRetryOn.");
bool retry = false;
SqlException sqlException = GetSqlException(ex);
if (sqlException != null)
{
int[] errorsToRetry =
{
1205, //Deadlock
-2 //Timeout
};
if (sqlException.Errors.Cast<SqlError>().Any(x => errorsToRetry.Contains(x.Number)))
{
retry = true;
}
}
if (ex is TimeoutException)
{
retry = true;
}
return retry;
}
}
I'm not hitting anything at all in this particular piece of the code.
One thing that may be of note, is that every example I've seen so far (for example http://blog.analystcircle.com/2015/08/01/connection-resiliency-in-entity-framework-6-0-and-above/) has casted the exception in ShouldRetryOn directly to a SqlException using
SqlException sqlException = ex as SqlException;
I found that using this method always resulted in a null SqlException because my program is throwing an EntityException which can't be cast into a SqlException. My underlying SqlException is actually the inner exception of the inner exception of the EntityException. So, I put together a short recursive call to dig in and find it.
private SqlException GetSqlException(Exception ex)
{
SqlException result = ex as SqlException;
if (result == null && ex.InnerException != null)
result = GetSqlException(ex.InnerException);
return result;
}
This works properly, but the fact that I need to do it when the examples I've found don't is probably a clue as to what's going wrong. Do EntityExceptions not trigger a DbExecutionStrategy? If not, why is this listed as a solution to be used with EF 6? Any insight would be much appreciated.
EDIT:
Doing some more digging into the source for DbExecutionStrategy (https://github.com/aspnet/EntityFramework6/blob/master/src/EntityFramework/Infrastructure/DbExecutionStrategy.cs), I've found that my recursive function to find my SqlException from the EntityException is unnecessary. DbExecutionStrategy has a function UnwrapAndHandleException which does just that and passes the SqlException on to ShouldRetryOn. So, it seems I'm right back at square one.
EDIT 2:
Not really a solution, because it doesn't explain why my DbExecutionStrategy isn't being called as it should, but I have found that if I explicitly call the execution strategy, it works.
The code to use the execution strategy explicitly is:
var executionStrategy = new MyConfiguration.MyExecutionStrategy();
executionStrategy.Execute(
() =>
{
//build your context and execute db functions here
using (var context = new Entities())
{
...do stuff
}
});
Probably way too old by now but in case anyone is having the same issues:
exception.GetBaseException() gets you the root cause of any exception. No need for recursion
I'm able to get this to work using EF 6.4.0

Unit Testing void returning method

I am using Moq for the first time and not really sure on the correct approach for Testing a void returning method I have. I have read this post which was helpful but didnt include many snippets of code for guidance. My method updates my DB with responses from an external webservice for a list of my car objects
My method is as below:
public void UpdateDBWithWebResponse(Response response, List<Car> cars)
{
try
{
if (response == null)
{
//Exception logged
}
foreach (var webResponse in response.Responses)
{
var car = cars.First(c => c.Id == webResponse.Id);
if (response.detailResponse == null || response.detailResponse.Values == null)
{
//Exception logged
}
foreach (var detailResponse in response.HazardResponse.Values)
{
UpdateDetailResponseOnCar(detailResponse, car);
}
}
//update the DB
_carRepository.Update(cars);
}
catch (Exception ex)
{
//log error
}
}
So it takes two parameters a Web response object and a list of car objects - UpdateDetailResponseOnCar(detailResponse, car); is a private method which maps the web reponse to the car object and then the data is saved to the DB.
I guess what I want to Test is that if the response is null then an exception is called? Similariy with the inner detail response if null is exception thrown. And then if I create a Mock response object and a mock list of cars I want to save that to a Test instance of my DB and assert that the correct values were mapped?
Does this seem like a good strategy to test the above method and has anyone got any code snippets for testing the null response throws exception and for the other cases?
First, remove the catch around everything.
Ideally you would throw exceptions where absolutely necessary, and then allow the calling code to catch them.
That way you can catch the exception in your test.
Perhaps best to use specific exceptions, e.g. ArgumentNullException for the case when response is null.
See the following for MSTest:
http://www.contentedcoder.com/2012/01/asserting-exceptions-in-mstest-with.html
What testing framework are you using? If you're using something like NUnit, you can add the ExpectedException attribute. That works if the exception is uncaught. So in your UpdateDBWithWebResponse method, you could log and rethrow it perhaps.

Why does my ASP.NET MVC 3 with EF application only work when I step through it while debugging?

I have a controller that updates values in a database using Entity Framework. Unfortunately, when I run my application it doesn't seem to work at all. When I put breakpoints in and step through a specific part of the code, it works perfectly.
Here's my controller code:
public ActionResult ManageGame(int id, FormCollection collection, string[] selectedPlayers)
{
var gameToUpdate = db.Games
.Include("Teams")
.Where(g => g.ID == id)
.Single();
if (TryUpdateModel(gameToUpdate, "", null, new string[] { "Players" }))
{
try
{
List<Player> team1Players = generateRandomTeam();
List<Player> team2Players = generateRandomTeam();
If I put a breakpoint here and step through the rest of the code it's fine, otherwise nothing gets saved.
foreach (var team in gameToUpdate.Teams)
{
if (!team1added)
{
team.Players = team1Players;
team1added = true;
}
else
{
team.Players = team2Players;
}
}
db.Entry(gameToUpdate).State = EntityState.Modified;
db.SaveChanges();
}
catch (DataException)
{
ModelState.AddModelError("", "Unable to save changes.");
}
}
try
{
return RedirectToAction("Index");
}
catch
{
return View();
}
}
I have a feeling it's the way I'm assigning the new teams to the existing context, but from all the tutorials I've read, this is the way they do it, at least for string values. Does anybody know why I'm getting this bizarre behavior?
*UPDATE* SOLVED
I solved my problem. My hunch was right, I just needed to add team.Players.Clear() before assigning the new group of players to the existing team.
foreach (var team in gameToUpdate.Teams)
{
if (!team1added)
{
team.Players.Clear()
team.Players = team1Players;
team1added = true;
}
else
{
team.Players.Clear()
team.Players = team2Players;
}
}
When I didn't have that, I got a primary key violation exception. Unfortunately I didn't see this exception, because my code was swallowing this as pointed out by DarK. So, after adding the Clear() method everything worked like a charm.
Looks like other people have had the same problem like yours. Have alook at these links: C# code only gives expected results on step through?, Code runs correctly only when stepping through it with debugger?
So, if you are instantiating the Random class more than once, you will get some weird results.
EDIT:
From your code, it looks like you're consuming the exception. Can you possibly comment out the try-catch and run it without debugging and see if it throws any exceptions?

Try Catch not working in MVC3

try
{
var orderedListOfRfidTags = uow.RfidTags.ToList().OrderBy(t => int.Parse(t.Number));
return View(orderedListOfRfidTags);
}
catch
{
var orderedListOfRfidTags = uow.RfidTags.OrderBy(t => t.Number).ToList();
return View(orderedListOfRfidTags);
}
MVC3 - in Release mode this will still fail on the first line var ordreedListOfRfidTags...
I wonder why try catch isn't trying and catching?
then pressing F10 it goes to here.. which is part of my ORM wrapper... hmm I wonder if this is the problem.
protected override void OnResultExecuted(ResultExecutedContext filterContext)
{
if (_unitOfWorkScope != null)
{
_unitOfWorkScope.Dispose();
}
base.OnResultExecuted(filterContext);
}
The delegate passed to OrderBy is not invoked until you try to access the elements in the list.
So I think the error is not caught because your collection is not enumerated until the view is being rendered, after the action method has returned.
This is a bad design; you shouldn't have any code in your catch that could potentially throw another exception.
If I'm understanding your code, you want to attempt to parse the RFID to an int, but fall back on string as your sort if a failure?
If you can't gaurentee that the Numbers of the RfidTags won't be a number (which seems a silly naming structure), then I'd leave it as a string sort and ditch the int parsing
The answer was that LightSpeed was failing out. Once the support was added (very quickly - awesome product!) it all worked fine:
// trying to convert to an int.. if fail, use string
// need up to date nightly build of LS3.1 for this to work
// otherwise trycatch will fail due to LS crashing out.
try
{
var orderedListOfRfidTags = uow.RfidTags
.OrderBy(t => Convert.ToInt32(t.Number))
.ToList();
return View(orderedListOfRfidTags);
}
catch
{
var orderedListOfRfidTags = uow.RfidTags
.OrderBy(t => t.Number)
.ToList();
return View(orderedListOfRfidTags);
}

Annoying SQL exception, probably due to some code done wrong

I started working on this "already started" project, and I'm having a really annoying error when trying to execute some interactions with SQL Server 2008:
The server failed to resume the
transaction. Desc.:
One of these errors I get in this specific method call:
The aspx.cs Call:
busProcesso openProcess = new busProcesso(pProcessoId);
try
{
if (openProcess.GetDocument() == null)
{
//Irrelevant code.
}
}
catch{ //... }
The Business class (relevant part):
public class busProcesso : IbusProcesso
{
public Processo vProcesso { get; set; }
RENDBDataContext db;
public busProcesso()
{
vProcesso = new Processo();
}
public busProcesso(decimal pProcessoId)
{
db = new RENDBDataContext();
try
{
vProcesso = db.Processos.SingleOrDefault(x => x.Id == pProcessoId);
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
public string GetDocument()
{
try
{
string document = null;
foreach (Processo_has_Servico ps in ListaServicosProcesso())
{
if (ps.Servico.Document != null) //Get the error right at this line.
{
document = ps.Servico.Document;
}
}
return document ;
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
public IQueryable<Processo_has_Servico> ListaServicosProcesso()
{
db = new RENDBDataContext();
try
{
return from ps in db.Processo_has_Servicos
join s in db.Servicos on ps.Servico_Id equals s.Id
where ps.Processo_Id == vProcesso.Id
select ps;
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
}
As I said, the error occurs right at the line:
if (ps.Servico.Document != null) from the GetDocument() method.
Opening SQL Server Activity Monitor, I see there is a process for my database (.Net SqlClient Data Provider)
After some time/use (when I start to get the "server failed to resume the transaction" error), I go to the SQL Server Activity Monitor and there's around 5 or 6 more identical processes that weren't killed and (probably) should've been. When I manually kill them, the error stops for a while, until it starts again.
I'm not really good at working in OO and all, so I'm probably missing something, maybe some way to close one of these connections. Also, any help/tip about this structure will be welcome.
PS. The error doesn't happen everytime. Sometimes it runs just perfectly. Then it starts to give the error. Then it stops. Sometimes it happens just once.. pretty weird.
The code in ListaServicosProcesso is creating the context db. Then it is returning an IQueryable.
At this point no request has been sent to the database.
Then there is a for each in the code. At this point EF says "I need to get the data from the database". So it tries to get the data.
But the context db is now out of scope, so it crashes, on the first line that tries to use the data.
There are 2 ways to get around this:
return a list from ListaServicosProcesso, this will force the database call to execute
move the for each into ListaServicosProcesso
Edit
Pharabus is correct db is not out of scope. The problem is here:
db = new RENDBDataContext();
A new instance of the context is being created without the old one being disposed. Try Dispose of db at the end of ListaServicosProcesso. Even better place db in a using statement. But then the foreach must be moved inside the using statement.
Here's a couple of ideas to try.
1/ You can attach SQL server profiler to see the query that is being executed, which will allow you to copy and paste that query to see the data that is in the database. This might be help.
2/ You never check whether ps.Servico is null - you jump straight to ps.Servico.Document. If ps.Servico is null then you will get a null reference exception if you try to access any properties on that object.
I'm not sure of the exact cause of the error you're seeing (if you Google it, the references are all over the place...), but there are a few things you could improve in your code and I've found that just cleaning things up a bit often makes problems go away. Not always, but often.
I agree with the other answerers that it would help to keep better track of your DataContext(s). For example in you're creating it once in the constructor, then again in ListaServicosProcesso(). At that point vProcesso is on one DataContext and other entities will be on another, which gets messy.
I think you could simplify the whole thing a bit, for example you could combine GetDocument() and ListaServicosProcesso() like this:
public string GetDocument()
{
try
{
// Are you sure vProcesso is not null?
if (vProcesso == null)
return null;
// Only create the context if it wasn't already created,
if (db == null)
db = new RENDBDataContext();
return db.Processo_has_Servicos
.Where(ps => ps.Processo_Id == vProcesso.Id && ps.Servico.Document != null)
.Select(ps => ps.Servico.Document) // use an implicit join
.SingleOrDefault();
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}

Categories

Resources