Effort throws InvalidOperationException: Sequence contains more than one matching element - c#

I'm using Effort in a regular way by creating a connection and passing it to DB Context:
public class InMemoryContextInitializer
{
public void BeforeAllTests()
{
Effort.Provider.EffortProviderConfiguration.RegisterProvider();
}
public DbConnection BeforeEachTest()
{
return Effort.DbConnectionFactory.CreateTransient();
}
public void AfterEachTest(DbConnection prevUsedConnection)
{
prevUsedConnection.Dispose();
}
}
and something like this:
private static InMemoryContextInitializer _testHarness;
private DbConnection _conn;
private MyDbContext _myContext;
[ClassInitialize]
public static void BeforeAllTests(TestContext testCtx)
{
_testHarness = new InMemoryContextInitializer();
_testHarness.BeforeAllTests(); // registers provider
}
[TestInitialize]
public void BeforeTest()
{
_conn = _testHarness.BeforeEachTest();
_myContext = new MyDbContext(_conn);
}
[TestCleanup]
public void AfterTest()
{
_testHarness.AfterEachTest(_conn);
}
All my Effort tests pass just fine except one which throws this:
System.Data.DataException: An exception occurred while initializing the database. See the InnerException for details. --->
System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. --->
System.Data.Entity.Core.UpdateException: An error occurred while updating the entries. See the inner exception for details. --->
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. --->
NMemory.Exceptions.NMemoryException: Error code: GenericError --->
System.InvalidOperationException: Sequence contains more than one matching element
at System.Linq.Enumerable.SingleOrDefault(IEnumerable`1 source, Func`2 predicate)
at NMemory.Tables.TableCollection.FindTable(Type entityType)
at NMemory.Utilities.TableCollectionExtensions.FindTable(TableCollection tableCollection)
at NMemory.Execution.CommandExecutor.ExecuteInsert(T entity, IExecutionContext context)
at NMemory.Tables.DefaultTable`2.InsertCore(TEntity entity, Transaction transaction)
at Effort.Internal.DbManagement.Engine.ExtendedTable`2.InsertCore(TEntity entity, Transaction transaction)
at NMemory.Tables.Table`2.Insert(TEntity entity, Transaction transaction)
--- End of inner exception stack trace ---
at NMemory.Tables.Table`2.Insert(TEntity entity, Transaction transaction)
at Effort.Internal.Common.DatabaseReflectionHelper.WrapperMethods.InsertEntity(ITable`1 table, TEntity entity, Transaction transaction)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Effort.Internal.Common.DatabaseReflectionHelper.InsertEntity(ITable table, Object entity, Transaction transaction)
at Effort.Internal.CommandActions.InsertCommandAction.CreateAndInsertEntity(ITable table, IList`1 memberBindings, Transaction transaction)
at Effort.Internal.CommandActions.InsertCommandAction.ExecuteNonQuery(ActionContext context)
at Effort.Provider.EffortEntityCommand.ExecuteNonQuery()
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext`1 c)
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch(TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues)
at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
--- End of inner exception stack trace ---
at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<Update>b__2(UpdateTranslator ut)
at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update(T noChangesResult, Func`2 updateFunction)
at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update()
at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction(Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction)
at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass2a.<SaveChangesInternal>b__27()
at System.Data.Entity.Infrastructure.DefaultExecutionStrategy.Execute(Func`1 operation)
at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction)
at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options)
at System.Data.Entity.Internal.InternalContext.SaveChanges()
--- End of inner exception stack trace ---
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
at System.Data.Entity.Migrations.History.HistoryRepository.BootstrapUsingEFProviderDdl(VersionedModel versionedModel)
at System.Data.Entity.Internal.InternalContext.<SaveMetadataToDatabase>b__7()
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
at System.Data.Entity.Internal.InternalContext.SaveMetadataToDatabase()
at System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext, Func`3 createMigrator, ObjectContext objectContext)
at System.Data.Entity.Internal.InternalContext.CreateDatabase(ObjectContext objectContext, DatabaseExistenceState existenceState)
at System.Data.Entity.Database.Create(DatabaseExistenceState existenceState)
at System.Data.Entity.CreateDatabaseIfNotExists`1.InitializeDatabase(TContext context)
at System.Data.Entity.Internal.InternalContext.<>c__DisplayClassf`1.<CreateInitializationAction>b__e()
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
--- End of inner exception stack trace ---
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
at System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c)
at System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)
at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
at System.Linq.Queryable.Count(IQueryable`1 source)
at Model.MyProj... my test method call stack here
I use multiple DB contexts in these tests and it all works except for this case:
var query = db.MyEntities.Count(); // will throw the exception above ONLY FOR SOME DB CONTEXTS
In fact any operation on this context like Add will throw.
I could not find anyone having the same problem on Effort website or by googling. Maybe it's a bug? I'm using the latest version of Effort - 1.1.4 and Entity Framework - 6.1.3.
I checked for any special thing about DbContext or the entity class and didn't find anything.

I had this issue and found that using a separate connection (Effort.DbConnectionFactory.CreatePersistent) for each context solved the issue.
In my case, each context operates over entirely different tables, so there shouldn't have been a conflict in Effort / NMemory - so I think the bug report is sound - but this information may unblock people in the meantime.
The trade off is that this could be warning you that you actually do have two contexts operating on the same table, which would be bad - so you'll have to watch out for this too.

Related

GetToastCollectionManager crash

I already have Toast Notifications working, but I need to create a collection for them.
Following the code example in : https://learn.microsoft.com/en-us/windows/apps/design/shell/tiles-and-notifications/toast-collections
I get a crash on the GetToastCollectionManager call.
System.Exception
HResult=0x80070490
Message=Element not found. (0x80070490)
Source=<Cannot evaluate the exception source>
StackTrace:
<Cannot evaluate the exception stack trace>
This exception was originally thrown at this call stack:
WpfApp1.MainWindow.CreateToastCollection() in MainWindow.xaml.cs
I'm not sure if I'm missing something obvious , but I cannot find examples or tutorials on Toast Notifications.
Any Ideas ?
public async void CreateToastCollection()
{
ToastNotificationManagerForUser defaultManager = ToastNotificationManager.GetDefault();
ToastCollectionManager collectionManager = defaultManager.GetToastCollectionManager();
string displayName = "Is Potato";
string launchArg = "NavigateToPotato";
System.Uri iconURI = new System.Uri("ms-appx:///Assets/icon.png");
ToastCollection licensingManagerToastCollection = new ToastCollection(
"MyToastCollection",
displayName,
launchArg,
iconURI);
// Calls the platform to create the collection
await collectionManager.SaveToastCollectionAsync(licensingManagerToastCollection);
}

Why is my stack trace being truncated?

I have a partial-trust AppDomain within which I run a full-trust debugging window. Using PermissionSetAttribute to get permissions I can create the window and do plenty of things with it, but sometimes a SecurityException will be thrown during data binding.
One easily reproducible case throws this: Property accessor 'Namespace' on object 'System.RuntimeType' threw the following exception:'Request failed.'. Digging into the exception I can see that it was thrown when full trust was demanded.
No problem, the debug window assembly has full trust and I simply need to assert it. But when I look at the stack trace of the inner SecurityException I see this:
at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)
at System.Security.CodeAccessSecurityEngine.Check(PermissionSet permSet, StackCrawlMark& stackMark)
at System.Security.PermissionSet.Demand()
at System.SecurityUtils.DemandGrantSet(Assembly assembly)
at System.SecurityUtils.DemandReflectionAccess(Type type)
at System.SecurityUtils.MethodInfoInvoke(MethodInfo method, Object target, Object[] args)
at System.ComponentModel.ReflectPropertyDescriptor.GetValue(Object component)
It ends right there, at ReflectPropertyDescriptor.GetValue.
In Visual Studio's Call Stack window I can see ReflectPropertyDescriptor.GetValue at the very tip of the stack. That stack goes all the way back to the creation of the debug window and the security assert I performed there, which is exactly what I want.
Why has the stack been split in two like this? How can I stop it from happening?
I'm using .Net 4.0 security (i.e. Level 2).
This isn't that odd. Visual studio's call stack is showing you the method which you were at when the current exception was thrown . The InnerException shows the callstack of where the inner exception exception occurred. After the inner exception was thrown, it propagated up the callstack thus unwinding it until it got to ReflectPropertyDescriptor.GetValue. At that point, it was caught in a catch block and set as the inner exception of a new exception which then thrown and bubbled all the way up. So the call stack for the second exception begins at the point it was thrown (i.e. ReflectPropertyDescriptor.GetValue)
Here's a simple example which reproduces this.
namespace Exceptions
{
class ExceptionTester
{
public void Run()
{
ThrowSecondException();
}
public void DoSomething()
{
DoMore();
}
public void DoMore()
{
ThrowFirstException();
}
public void ThrowFirstException()
{
throw new FooException();
}
public void ThrowSecondException()
{
try
{
DoSomething();
}
catch (FooException e)
{
throw new BarException("derp", e);
}
}
}
class FooException : Exception
{
}
class BarException : Exception
{
public BarException(string msg, Exception inner) : base(msg, inner)
{
}
}
class Program
{
static void Main(string[] args)
{
var tester = new ExceptionTester();
tester.Run();
}
}
}
When the second exception of type BarException is thrown, you'll notice that visual studio has ThrowSecondException at the top of the call stack because that is where BarException was thrown. However, when you dig into BarException's InnerException and look at FooException's call stack, it'll show you where FooException was thrown (ThrowFirstException()).

odata unknown function cast

I have a web api project that host my models, in my .net application, when I query this :
static void TitleById(MoviesService.Container container, short id)
{
try
{
MoviesService.Title title = container.Title.Where(w => w.Id == id).SingleOrDefault();
if (title != null)
{
DisplayTitle(title);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
the problem is not with the query, it's from id variable. the id variable is of the short type not an int. here is the exception message :
<?xml version="1.0" encoding="utf-8"?>
<m:error xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
<m:code />
<m:message xml:lang="en-US">An error has occurred.</m:message>
<m:innererror>
<m:message>Unknown function 'cast'.</m:message>
<m:type>System.NotImplementedException</m:type>
<m:stacktrace> at System.Web.Http.ApiController.<InvokeActionWithExceptionFilters>d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__0.MoveNext()</m:stacktrace>
</m:innererror>
</m:error>
and here is odata url :
"GET http://localhost:21401/odata/Title()?$filter=cast(Id,'Edm.Int32') eq 3&$top=2"
well, the type of Id property in my entites is short. how can I pass it to the query?
Thanks, If I have to bring more information, please tell me.
I found that cast is not implemented in FilterBinder.BindSingleValueFunctionCallNode in source code:
https://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Http.OData/OData/Query/Expressions/FilterBinder.cs
One of the way to solve it is to download the code and implement yourself.

System.AggregateException on Socket.EndAccept with TaskFactory.FromAsync

I am working with async operations with sockets (.Net 4 - VS 2010 SP1) and all seems to be working okay. However, after write and run an automated test, it pass green but displays an exception message:
---- UNHANDLED EXCEPTION ----
Thread Name: <No Name>
System.AggregateException: A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread. ---> System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Sockets.Socket'.
at System.Net.Sockets.Socket.EndAccept(IAsyncResult asyncResult)
at P2PNet.Listener.<ListenForConnections>b__0(IAsyncResult r) in C:\Users\lucas.ontivero\Documents\Visual Studio 2010\Projects\P2PNet\P2PNet\Listener.cs:line 76
at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endMethod, TaskCompletionSource`1 tcs)
--- End of inner exception stack trace ---
at System.Threading.Tasks.TaskExceptionHolder.Finalize()
---> (Inner Exception #0) System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Sockets.Socket'.
at System.Net.Sockets.Socket.EndAccept(IAsyncResult asyncResult)
at P2PNet.Listener.<ListenForConnections>b__0(IAsyncResult r) in C:\Users\lucas.ontivero\Documents\Visual Studio 2010\Projects\P2PNet\P2PNet\Listener.cs:line 76
at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endMethod, TaskCompletionSource`1 tcs)<---
I know what that exception means, it means the socket was closed before the EndAccept method was called. I have no problems with that, what I really don´t know is how to prevent that exception in an elegant way. This is my code:
private void ListenForConnections()
{
try
{
Task.Factory.FromAsync<Socket>(_listener.BeginAccept, _listener.EndAccept, _listener)
.ContinueWith(task =>
{
if (task.IsFaulted) return;
ListenForConnections();
var newSocket = task.Result;
RaiseClientConnectedEvent(new ConnectionEventArgs(newSocket));
}, TaskContinuationOptions.OnlyOnRanToCompletion);
}
catch (ObjectDisposedException)
{
}
I´ve tried with the line:
if (task.IsFaulted) return;
and also with:
.ContinueWith(task=>{}, TaskContinuation.OnlyOnFault);
But the exception is thrown anyway. Which is the way to prevent the exception?
Thank you!
Your line:
if (task.IsFaulted) return;
Is returning not faulted because you are checking the continuation task's status, not the preceding task. Change it to this:
private void ListenForConnections() {
Task<Socket> listentask = Task.Factory.FromAsync<Socket>(_listener.BeginAccept, _listener.EndAccept, _listener);
listentask.ContinueWith(task => {
if (listentask.IsFaulted) {
//observe exception
Exception exception = listentask.Exception;
return;
}
ListenForConnections();
var newSocket = listentask.Result;
RaiseClientConnectedEvent(new ConnectionEventArgs(newSocket));
});
//don't forget to start it
listentask.Start();
}
You need to observe the exception by reading the Exception property. Do that inside of your continuation.

What causes a System.Runtime.InteropServices.COMException at BackgroundAudioPlayer.get_Position()?

Sometimes I'm getting an exception when trying to get the position of the BackgroundAudioPlayer.Instance. It's happening very rarely, but I've been able to get a StackTrace. The strange thing is, this code is executed every second while playing a track. What could be the cause of this error?
I'm getting this StackTrace.
System.SystemException: HRESULT = 0xC00D36C4 ---> System.Runtime.InteropServices.COMException: Exception from HRESULT: 0xC00D36C4 at
Microsoft.Phone.BackgroundAudio.Interop.IAudioPlaybackManager.get_CurrentPosition() at
Microsoft.Phone.BackgroundAudio.BackgroundAudioPlayer.get_Position() --- End of inner exception stack trace --- at
Microsoft.Phone.BackgroundAudio.BackgroundAudioPlayer.get_Position() at
MC.PodCast.Common.ViewModel.PlayerViewModel.UpdateTrackPosition() at
MC.PodCast.Common.ViewModel.PlayerViewModel.ReactToBackgroundAudioPlayer() at
MC.PodCast.Common.ViewModel.PlayerViewModel.Initialize() at
MC.PodCast.Common.ViewModel.PlayerViewModel.<<get_InitializeCommand>b__5>d__6.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<ThrowAsync>b__0(Object state)
Of course the code I'm using is just plain simple.
public void UpdateTrackPosition()
{
if (_backgroundAudioPlayer != null && _backgroundAudioPlayer.Track != null)
{
Position = _backgroundAudioPlayer.Position;
}
else
{
Position = null;
}
}
That code is linked to MF_MEDIA_ENGINE_ERR_SRC_NOT_SUPPORTED but I'm guessing that you do have sound.
I have found that the BackgroundAudioPlyer can be very weird. I wrap most of my calls with a "Safe" extension method.
Example
public static PlayState PlayerStateSafe(this BackgroundAudioPlayer source)
{
PlayState state;
try
{
state = source.PlayerState;
}
catch (InvalidOperationException)
{
state = PlayState.Unknown;
}
return state;
}

Categories

Resources