odata unknown function cast - c#

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.

Related

Cloud firestore WhereIn method not working in .Net

I am using google.cloud.firestore package in .net core and I want to query the documents that have a specific field value existing in a provided list of values (like the IN command in sql). I came across the WhereIn method but I keep getting an exception. I have been trying for the last few hours but no success!
Here is the code:
public async Task<List<Document>> GetListByAccountRef(List<string> accountRefs)
{
var docRef = _Firestore.Collection("documents").WhereIn("AccountRef", accountRefs);
var docsQuery = await docRef.GetSnapshotAsync();
var docs = docsQuery.Select(d => d.ConvertTo<Document>()).ToList();
return docs;
}
I get an exception on the second line:
var docsQuery = await docRef.GetSnapshotAsync();
This is the error message:
Status(StatusCode=InvalidArgument, Detail="Unknown FieldFilter operator.")
And here is the stacktrace:
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Grpc.Core.Internal.ClientResponseStream`2.<MoveNext>d__5.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Linq.AsyncEnumerable.<ForEachAsync_>d__174`1.MoveNext() in
D:\a\1\s\Ix.NET\Source\System.Interactive.Async\ForEach.cs:line 141
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Google.Cloud.Firestore.Query.<GetSnapshotAsync>d__54.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Docer.DAL.Repositories.DocumentRepository.<GetListByAccountRef>d__7.MoveNext() in E:\Docer\webapp-
FireStore-Branch\Docer.DAL\Repositories\Document\DocumentRepository.cs:line 84
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Docer.BLL.Doc.DocumentBusiness.<GetUserDocuments>d__10.MoveNext() in E:\Docer\webapp-FireStore-
Branch\Docer.BLL.Doc\Document\DocumentBusiness.cs:line 84
Any help is appreciated, thanks.
This worked for me. You can follow the tutorial (https://pieterdlinde.medium.com/netcore-and-cloud-firestore-94628943eb3c)
List<Cities> cities = new List<Cities>()
{
new Cities()
{
CityName="tests"
}
};
Query employeeQuery = fireStoreDb.Collection(nameof(Employee)).WhereIn("City", cities);
QuerySnapshot employeeQuerySnapshot = await employeeQuery.GetSnapshotAsync();
Thanks to Jon, the problem appeared to be from the old version of the firestore emulator that I was using. After updating the emulator, it's working fine.

How to test that my stacktrace walker correctly skips library code

My question is: I am trying to skip some stackframes that come from library code. If I want to test this, how do I best/easiest force a situation where the stacktrace has one or more frames on top that come from library code?
Details:
My goal with the code below is to be able to log the origin of an exception in my source code. However, in some cases the exception is triggered in library code, so I get a stacktrace that looks like this:
System.Net.WebException: The operation has timed out
at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
at System.Net.HttpWebRequest.GetRequestStream()
at Microsoft.Bing.Platform.ConversationalUnderstanding.ObjectStore.ObjectStoreClientHelperClass.d__7``2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bing.Platform.ConversationalUnderstanding.ObjectStore.ObjectStoreCoprocRequest.d__10`4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
So basically I want to move on down the stackframes until I hit a spot where I have actual useful information, skipping the library methods that don't really tell me anything useful.
Here's the code I want to test:
public static (string Path, string Method, int Line) TryGetExceptionOrigin(this Exception e, string defaultPath, string defaultMethod, int defaultLine)
{
var defaultRes = (Path: defaultPath, Method: defaultMethod, Line: defaultLine);
var st = new StackTrace(e.GetInnerMostException(), true);
if (st.FrameCount == 0)
{
return defaultRes;
}
// Walk down the stack, ignoring framework code etc. with no useful information. We need a file name to be happy
for (int i = 0; i < st.FrameCount; i++)
{
var bottomFrame = st.GetFrame(i);
if (!(string.IsNullOrEmpty(bottomFrame.GetFileName())))
{
return (
Path: bottomFrame.GetFileName() ?? string.Empty, // Is null if no debug information
Method: bottomFrame.GetMethod().Name, // Documentation does not say this can ever be null
Line: bottomFrame.GetFileLineNumber()); // Is 0 if no debug information
}
}
// OK no match, we return the default information
return defaultRes;
}
Some unnecessarily convoluted stuff like this should do nicely:
try
{
Func<int> d = () =>
{
try
{
return Guid.Parse("*").ToByteArray()[0];
}
catch (Exception)
{
throw;
}
};
Action a = () => { String.Format("{0}", 1 / d()); };
a();
}
catch (Exception ex)
{
var useful = ex.TryGetExceptionOrigin(null, null, 0);
}
This example results in an exception call stack with three user code and four framework/library code entries.
Found it at https://dotnetthoughts.wordpress.com/2007/10/27/where-did-my-exception-occur/
private static void ThrowIt()
{
Divide(3M, 0M);
}
static decimal Divide(decimal a, decimal b)
{
return (a / b);
}
This will produce this stacktrace:
st {
at System.Decimal.FCallDivide(Decimal& d1, Decimal& d2)
at System.Decimal.op_Division(Decimal d1, Decimal d2)
at ExceptionLogging.Program.Divide(Decimal a, Decimal b) in C:\Users\anjohans\source\repos\ExceptionLogging\ExceptionLogging\Program.cs:line
98 at ExceptionLogging.Program.ThrowIt() in
C:\Users\anjohans\source\repos\ExceptionLogging\ExceptionLogging\Program.cs:line
93 at ExceptionLogging.Program.ThrowLater() in
C:\Users\anjohans\source\repos\ExceptionLogging\ExceptionLogging\Program.cs:line
88 at ExceptionLogging.Program.Main(String[] args) in
C:\Users\anjohans\source\repos\ExceptionLogging\ExceptionLogging\Program.cs:line
17 } System.Diagnostics.StackTrace

GetWorkItemAsync method exception when called from multiple threads C#.Net

I am trying to get the links from VSO for workitems, and the code seems to work fine when called from a single thread, but throws exceptions when called from a parallel for each loop.
I initalize my vso client object in my class's constructor:
vso = new WorkItemReporting(Config.VSTSAccessToken);
Then later in a method:
Parallel.ForEach(msrcAbBugsToProcess, new ParallelOptions { MaxDegreeOfParallelism = 10 }, bugId =>
{
var workItemLinks = vso.GetWorkItemSourceCodeLinks(bugId);
});
witclient below is a WorkItemTrackingHttpClient which is in a different class (WorkItemReporting) and calls the API. It is this call that fails.
public List<string> GetWorkItemSourceCodeLinks(int bugId)
{
var workItemSourceCodeLinks = new List<string>();
var workItem = _witClient.GetWorkItemAsync(bugId, null, null, WorkItemExpand.Relations).Result;
if (workItem?.Relations != null)
{
var validSourceCodeLinkTypes = new List<string> { "ArtifactLink", "Hyperlink" };
foreach (var relation in workItem.Relations)
{
if (validSourceCodeLinkTypes.Contains(relation.Rel))
{
workItemSourceCodeLinks.Add(relation.Url);
}
}
}
}
This works fine if I don't use the Parallel.ForEach and I get the needed data from the API. When I do, I get this exception 50% of the time:
Object reference not set to an instance of an object.
at System.Security.Cryptography.X509Certificates.X509CertificateCollection.GetHashCode()
at System.Net.HttpWebRequest.GetConnectionGroupLine()
at System.Net.HttpWebRequest.SubmitRequest(ServicePoint servicePoint)
at System.Net.HttpWebRequest.BeginGetResponse(AsyncCallback callback, Object state)
at System.Net.Http.HttpClientHandler.StartGettingResponse(RequestState state)
at System.Net.Http.HttpClientHandler.StartRequest(Object obj)
--- 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.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at Microsoft.VisualStudio.Services.Common.VssHttpMessageHandler.<SendAsync>d__17.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 Microsoft.VisualStudio.Services.Common.VssHttpRetryMessageHandler.<SendAsync>d__4.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 Microsoft.VisualStudio.Services.WebApi.VssHttpClientBase.<SendAsync>d__48.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 Microsoft.VisualStudio.Services.WebApi.VssHttpClientBase.<SendAsync>d__45`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 Microsoft.VisualStudio.Services.WebApi.VssHttpClientBase.<SendAsync>d__27`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 Microsoft.VisualStudio.Services.WebApi.VssHttpClientBase.<SendAsync>d__26`1.MoveNext()
Is there something I'm doing wrong?
A solution is to create WorkItemReporting inside Parallel.ForEach:
Parallel.ForEach(msrcAbBugsToProcess, new ParallelOptions { MaxDegreeOfParallelism = 10 }, bugId =>
{
var vso = new WorkItemReporting(Config.VSTSAccessToken);
var workItemLinks = vso.GetWorkItemSourceCodeLinks(bugId);
});
You need to lock access to the external resource by doing something like the following.
As per comment #AlexSikilinda _witClient must not be thread safe.
For what your doing though, just because you can create multiple threads doesn't means you should, i would get timings, on what your doing with and without the parallel processing in your code,
Keep in mind if you use non thread safe external resources, and locks then it maybe just as slow as running in a normal for loop. You need to test both scenario's.
Add an object outside your methods to allow access to the lock object from every thread, this will help manage the access to the non thread safe class.
vso = new WorkItemReporting(Config.VSTSAccessToken);
private readonly object _witLock = new object();
In the following you DON'T want to put the lock around the entire methods contents as i have, otherwise you are definitely wasting your time using the Parallel for this piece of code.
Based on what your doing thought this should stop the exceptions.
You need refactor the code so that only the call to _witClient is within the lock. So just declare the workItem variable outside the lock with it proper type, and then only wrap the call to workItem = _witClient.GetWorkItemAsync(bugId, null, null, WorkItemExpand.Relations).Result; in your lock code.
public List<string> GetWorkItemSourceCodeLinks(int bugId)
{
var workItemSourceCodeLinks = new List<string>();
lock (_witLock)
{
var workItem = _witClient.GetWorkItemAsync(bugId, null, null, WorkItemExpand.Relations).Result;
if (workItem?.Relations != null)
{
var validSourceCodeLinkTypes = new List<string> { "ArtifactLink", "Hyperlink" };
foreach (var relation in workItem.Relations)
{
if (validSourceCodeLinkTypes.Contains(relation.Rel))
{
workItemSourceCodeLinks.Add(relation.Url);
}
}
}
}
}
Good Luck

Effort throws InvalidOperationException: Sequence contains more than one matching element

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.

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