My WPF application consists of a main TabControl which renders multiple plugins, loaded via MEF. Technically, the ICollectionView of the plugins-collection is bound to the ItemsSource-property of the main TabControl. The IsSynchronizedWithCurrentItem-property is also set to True to keep track of the currently selected tab item.
To initialize the plugins, I subscribe the CurrentChanged-event of the ICollectionView to initialize the selected plugin via lazy loading. Since lots of the initialization tasks are async, I also declared the event handler as async.
private ICollectionView pluginsCv;
public ICollectionView PluginsCv
{
get
{
if (pluginsCv == null)
{
pluginsCv = CollectionViewSource.GetDefaultView(Plugins);
pluginsCv.CurrentChanged += async (sender, args) =>
{
await LoadCurrentSection();
};
}
return pluginsCv;
}
}
Tasks of the LoadCurrentSection-method:
Check if data was already loaded before.
If not, initialize the currently selected plugin, inter alia, reading data via EntityFramework.
LoadCurrentSection-method:
private async Task LoadCurrentSection()
{
// If no tab is selected, select the first one
if (PluginsCv.CurrentItem == null)
{
// Comment for stackoverflow: Another raise of the CurrentChanged-event does not seem to be the cause. Tried to prevent another execution of LoadCurrentSection via a bool flag, an stayed in this method (no return statement). Same result.
PluginsCv.MoveCurrentToFirst();
return;
}
// Get the ViewModel of the currently selected section/plugin
var pluginViewModel = ((IPlugin)PluginsCv.CurrentItem).PluginElement.DataContext as ISettlementScheduleSection;
// Initialize currently selected section/plugin
if (pluginViewModel != null && !pluginViewModel.DataLoaded)
await pluginViewModel.LoadData();
}
LoadData-method of the plugin:
public override async Task LoadData()
{
// ...
Costs = await costsService.GetCosts(SubProjectId, UnitTypeId);
// ...
}
Every plugin holds it's own instances of service-classes for crud operations. Those disposable service classes hold and instance of the db-Context.
Little example:
public class CostsService : ServiceBase
{
public CostsService()
: base()
{ }
public CostsService(MyDbContext db)
{
this.Context = db ?? throw new ArgumentNullException(nameof(db));
}
public async Task<IEnumerable<CostsDefinition>> GetCosts(Guid subProjectId, Guid unitTypeId)
{
return await Context.CostsDefinitions.Where(cd => cd.SubProjectId == subProjectId
&& cd.UnitTypeId == unitTypeId)
.OrderBy(cd => cd.Year).ThenBy(cd => cd.Month)
.ToListAsync();
}
}
The db-context (Context-property) is not static and is also not shared between the plugins.
The Problem: Sometimes, but not always, this way to initialize the plugins causes a System.NotSupportedException: A second operation started on this context before a previous asynchronous operation completed. Use 'await' to ensure that any asynchronous operations have completed before calling another method on this context. Any instance members are not guaranteed to be thread safe. WPF seems to raise that event multiple times. To me it is unclear in what scenarios it gets raised. When the ICollectionView is first bound to the TabControl and the first item gets automatically selected? Also when I load and insert more plugins into the source collection? ...
Frequency of the bug: In this case, timing seems to play are role. The frequency of that bug changes when running without debugging or under different network conditions.
Workaround attempt: I tried to filter additional/unnecessary calls of the CurrentChanged-handler via a bool flag, but it didn't help in all cases. I just reduced the frequency a bit. I also tried to delegate every access to PluginsCv to the Dispatcher, but it didn't help. Also, I wrote debug information when pluginsCv is null. And I got that information only once, so the CurrentChanged-event must also be subscribed only once.
Exception details:
Source of exception: "EntityFramework"
Stacktrace:
at System.Data.Entity.Internal.ThrowingMonitor.EnsureNotEntered()
at System.Data.Entity.Core.Objects.ObjectQuery`1.System.Data.Entity.Infrastructure.IDbAsyncEnumerable<T>.GetAsyncEnumerator()
at System.Data.Entity.Internal.Linq.InternalQuery`1.GetAsyncEnumerator()
at System.Data.Entity.Infrastructure.DbQuery`1.System.Data.Entity.Infrastructure.IDbAsyncEnumerable<TResult>.GetAsyncEnumerator()
at System.Data.Entity.Infrastructure.IDbAsyncEnumerableExtensions.ForEachAsync[T](IDbAsyncEnumerable`1 source, Action`1 action, CancellationToken cancellationToken)
at System.Data.Entity.Infrastructure.IDbAsyncEnumerableExtensions.ToListAsync[T](IDbAsyncEnumerable`1 source, CancellationToken cancellationToken)
at System.Data.Entity.Infrastructure.IDbAsyncEnumerableExtensions.ToListAsync[T](IDbAsyncEnumerable`1 source)
at System.Data.Entity.QueryableExtensions.ToListAsync[TSource](IQueryable`1 source)
at xyz.desk.app.ccm.business.Service.CostsService.<GetCosts>d__7.MoveNext() in D:\Dev\ThatCrazyPluginProject\desk\app\xyz.desk.app.ccm.business\Service\CostsService.cs:line 89
--- 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`1.GetResult()
at xyz.desk.app.ccm.plugin.costplan.constructionprogress.ViewModel.ContructionProgressCostPlanViewModel.<LoadData>d__58.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.Runtime.CompilerServices.TaskAwaiter.GetResult()
at xyz.desk.app.ccm.plugin.settlementscheduleshost.ViewModel.SettlementSchedulesHostViewModel.<LoadCurrentSection>d__67.MoveNext() in D:\Dev\ThatCrazyPluginProject\desk\app\xyz.desk.app.ccm.ui\ViewModel\SettlementSchedulesHostViewModel.cs:line 307
--- 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.GetResult()
at xyz.desk.app.ccm.plugin.settlementscheduleshost.ViewModel.SettlementSchedulesHostViewModel.<LoadData>d__65.MoveNext() in D:\Dev\ThatCrazyPluginProject\desk\app\xyz.desk.app.ccm.ui\ViewModel\SettlementSchedulesHostViewModel.cs:line 282
--- 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.GetResult()
at xyz.desk.app.ccm.ui.ViewModel.ProjectViewModel.<LoadCurrentSection>d__115.MoveNext() in D:\Dev\ThatCrazyPluginProject\desk\app\xyz.desk.app.ccm.ui\ViewModel\ProjectViewModel.cs:line 763
--- 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.GetResult()
at xyz.desk.app.ccm.ui.ViewModel.ProjectViewModel.<<get_PluginsCv>b__21_0>d.MoveNext() in D:\Dev\ThatCrazyPluginProject\desk\app\xyz.desk.app.ccm.ui\ViewModel\ProjectViewModel.cs:line 120
Any ideas to solve this issue?
Typical race condition.
Lets consider this scenario
Thread1 - Access PluginsCv
PluginsCv is null so register CurrentChanged
Thread2 - Access PluginsCv
PluginsCv is null so register CurrentChanged
Later...
CurrentChanged fires
Thread1 - await LoadCurrentSection
Thread2 - await LoadCurrentSection
Thread2 "Wait! Thread1 is doing LoadCurrentSection too and its not done yet! Error! Error!"
Related
I'm using Microsoft Graph API library (C#) and wondering if anyone has experienced this:
Many of my graph API calls time out from time to time.
This can happen to any API call, from getting current user profile to getting sharepoint documents, and so on.
I've tried updating Microsoft Graph API and dependent Nuget packages to the latest versions, but it doesn't help.
To clarify, this application is a Windows console application. On Azure side, it is registered as a native application. As a test application, it is a single-threaded application. No concurrency, race conditions involved. Code logic is as simple as
User logs in.
The program makes a Graph API call (shown in eg.1) to get user's profile and this API call times out.
eg 1.
var currentUser = graphClient.Me.Request().GetAsync().Result;
eg 2.
var site = _graphClient.Sites[SharePointSiteId].Request().GetAsync().Result;
The symptom is after a minute or two, it throws an AggregationException(because of TPL) which includes a TimeOutException.
No unauthorized exception.
I want to know what could be the possible cause and how I can avoid that.
UPDATE:
Here's a screenshot when the exception happens.
UPDATE 2:
I've tried replacing all the API calls to use "await" directly to wait for results. because this example code is a console application. I put
static void Main(string[] args)
{
// using Stephen Cleary's nuget package: Nito.AsyncEx.Tasks
MainImp().WaitAndUnwrapException();
}
static async Task MainImp()
{
// ...
// Graph API calls
This exception is still thrown from this simple API call:
var currentUser = await graphClient.Me.Request().GetAsync();
An unhandled exception of type 'Microsoft.Graph.ServiceException' occurred in mscorlib.dll
Additional information: Code: timeout
Here's the full call stack
at Microsoft.Graph.HttpProvider.d__19.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.Graph.HttpProvider.d__18.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.Graph.BaseRequest.d__35.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.Graph.BaseRequest.d__311.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.Graph.UserRequest.<GetAsync>d__6.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.Runtime.CompilerServices.TaskAwaiter1.GetResult()
at SharePointConsoleApp.Program.d__14.MoveNext() in
D:\TestProjects\SharePointConsoleApp\Program.cs:line 133
--- 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
Nito.AsyncEx.Synchronous.TaskExtensions.WaitAndUnwrapException(Task
task) at SharePointConsoleApp.Program.Main(String[] args) in
D:\TestProjects\SharePointConsoleApp\Program.cs:line 50 at
System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[]
args) at System.AppDomain.ExecuteAssembly(String assemblyFile,
Evidence assemblySecurity, String[] args) at
Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state) at
System.Threading.ThreadHelper.ThreadStart()
First of all if it's an application with user interaction you should never do blocking (.Wait() or .Result) calls on the main thread, this will lock-up your application for further user interaction.
So you need to start by using async code, this is a sample of an async Button_Click handler. It will give you a warning, but this seems to be one of the use-cases of an async void.
private async void Button_Click(object sender, RoutedEventArgs
{
var currentUser = await graphClient.Me.Request().GetAsync();
// Presumably do something with the response
labelUser.Text = currentUser.DisplayName;
}
Few days ago I found a nice video about common async/await mistakes
You seem to be talking about a console app running on windows.
As of C# 7.1 you can also have an public static Task Main(string[] args) as starting point. Then your application would look like this:
public static async Task Main(string[] args) {
// Create the client here.....
var graphClient = .....;
// Await every call to the graphclient
var currentUser = await graphClient.Me.Request().GetAsync();
// Do something with the user
}
Maybe the reponse(payload) you get is very huge that while it processes the request times out? I had this issue frequently a while back while I was fiddling with graph api so i used pagination to limit the size/quantity of items sent back by it.
I've just experienced this and the cause was a corporate firewall was blocking traffic to graph.microsoft.com:443
This can be seen in wireshark as [TCP Retransmission]s after the initial request.
Unblocking this host resolved this issue for me.
I'm trying to insert records in two tables, but getting the exception. Could you please help me to resolve the issue.
First I tried the below code.
await _testRepository.InsertAsync(test);
await _xyzRepository.InsertAsync(xyz);
Then I tried this code, But nothing is working for me.
try
{
var test = new Test();
using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.RequiresNew))
{
int? tenantId = _unitOfWorkManager.Current.GetTenantId();
using (_unitOfWorkManager.Current.SetTenantId(tenantId))
{
await _testRepository.InsertAsync(test);
var xyz = new XYZ();
await _xyzRepository.InsertAsync(xyz);
await _unitOfWorkManager.Current.SaveChangesAsync();
await uow.CompleteAsync();
}
}
}
catch (Exception ex)
{
throw new UserFriendlyException(ex.Message);
}
Exception
Message:
Database operation expected to affect 1 row(s) but actually affected 0
row(s). Data may have been modified or deleted since entities were
loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for
information on understanding and handling optimistic concurrency
exceptions.
stack trace:
at
Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.ThrowAggregateUpdateConcurrencyException(Int32
commandIndex, Int32 expectedRowsAffected, Int32 rowsAffected) at
Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.d__4.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.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.d__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.EntityFrameworkCore.Update.ReaderModificationCommandBatch.d__32.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.EntityFrameworkCore.Update.Internal.BatchExecutor.d__10.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.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.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.EntityFrameworkCore.ChangeTracking.Internal.StateManager.d__61.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.EntityFrameworkCore.ChangeTracking.Internal.StateManager.d__59.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.EntityFrameworkCore.DbContext.d__48.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
Abp.EntityFrameworkCore.AbpDbContext.d__49.MoveNext()
in
D:\Github\aspnetboilerplate\src\Abp.EntityFrameworkCore\EntityFrameworkCore\AbpDbContext.cs:line
214
INFO 2018-04-11 13:59:53,439 [3 ]
ore.Mvc.Internal.ControllerActionInvoker - Executing action method
MyCompany.MyProject.AdditionalMasterData.Tests.TestsAppService.CreateOrEdit
(MyCompany.MyProject.Application) with arguments ([CreateOrEditTestDto
]) - ModelState is Valid WARN 2018-04-11 14:01:48,396 [4 ]
Mvc.ExceptionHandling.AbpExceptionFilter - Database operation expected
to affect 1 row(s) but actually affected 0 row(s). Data may have been
modified or deleted since entities were loaded. See
http://go.microsoft.com/fwlink/?LinkId=527962 for information on
understanding and handling optimistic concurrency exceptions.
Abp.UI.UserFriendlyException: Database operation expected to affect 1
row(s) but actually affected 0 row(s). Data may have been modified or
deleted since entities were loaded. See
http://go.microsoft.com/fwlink/?LinkId=527962 for information on
understanding and handling optimistic concurrency exceptions. at
MyCompany.MyProject.AdditionalMasterData.Tests.TestsAppService.d__7.MoveNext()
in
C:\Repo\MyProjectVenues\aspnet-core\src\MyCompany.MyProject.Application\AdditionalMasterData\Tests\TestsAppService.cs:line
205
--- 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
MyCompany.MyProject.AdditionalMasterData.Tests.TestsAppService.d__6.MoveNext()
in
C:\Repo\MyProjectVenues\aspnet-core\src\MyCompany.MyProject.Application\AdditionalMasterData\Tests\TestsAppService.cs:line
170
--- 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.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__12.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.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext
context) at
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State&
next, Scope& scope, Object& state, Boolean& isCompleted) at
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__14.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.AspNetCore.Mvc.Internal.ResourceInvoker.d__23.MoveNext()
Update
I have got the root cause of the issue.
So basically I have an insert trigger on Entity2 and When I have commented the query inside this trigger and then its working fine.
There are approximately 10 queries in this trigger and it's very hard to know which one is causing the problem. So could you please let me know how to debug this trigger?
I had a similar problem. I used EF Core. I was helped by the following change for my code.
context.Entry(user).State = EntityState.Added; // added row
this.context.Users.Add(user);
this.context.SaveChanges();
UPD: Sorry, problem has been solved by adding a Identity attribute for User.Id
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
Make sure in your repository function InsertAsync you are not calling AddAsync unless your are using the Microsoft.EntityFrameworkCore.Metadata.SqlServerValueGenerationStrategy.SequenceHiLo generator. AS NOTED IN the Docs. AddAsync
For my case, the problem caused when I tried to pass to Update() method an entity that didn't exist in database.
Issue with my code was, i was setting primary key value for tables explicitly, it's not db generated, but efcore was not aware about this.. so finally i need to write (ValueGeneratedNever)
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
//TODO: on add any entity add here the same
modelBuilder.Entity<AdminUser>().Property(e => e.AdminUserId).ValueGeneratedNever();
modelBuilder.Entity<AdminUserLogInLog>().Property(e => e.AdminUserLogInLogId).ValueGeneratedNever();
...........
}
Generic method for all table
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
foreach (var item in modelBuilder.Model.GetEntityTypes())
{
var p = item.FindPrimaryKey().Properties.FirstOrDefault(i=>i.ValueGenerated!=Microsoft.EntityFrameworkCore.Metadata.ValueGenerated.Never);
if (p!=null)
{
p.ValueGenerated = Microsoft.EntityFrameworkCore.Metadata.ValueGenerated.Never;
}
}
}
Make sure the generated SQL-query can actually reach the targeted row.
In my case the query looked like this:
UPDATE [Users] SET .....
WHERE [Id] = #p34 AND [ConcurrencyStamp] = null;
but 'ConcurrencyStamp' contained a not-null value so there was nothing to update.
I find that this can be a binding issue on the primary key(s). Check your query string to make sure that all is binding correctly in your view and update action. (make sure a query string value is not overwriting an input value).
Also you can check if your table have PK (primary key) identity option enabled.
If anyone arrives here with a background the same as mine, I had this error for an Add when I had a DateTime column as PK and this column was configured as .HasDefaultValueSql("getdate()").
I had to use the profiler to see that EFCore was sending NULL value for this column and trying to compare to the newly generated date:
exec sp_executesql N'SET NOCOUNT ON;
DECLARE #inserted0 TABLE ([Current_Nbr] nvarchar(450), [Db_Date] datetime2, [_Position] [int]);
MERGE [Current_Moves] USING (
VALUES (#p0, #p1, #p2, #p3, 0)) AS i ([Current_Nbr], [Despatch_Number], [Current_Loc], [Operator], _Position) ON 1=0
WHEN NOT MATCHED THEN
INSERT ([Current_Nbr], [Despatch_Number], [Current_Loc], [Operator])
VALUES (i.[Current_Nbr], i.[Despatch_Number], i.[Current_Loc], i.[Operator])
OUTPUT INSERTED.[Current_Nbr], INSERTED.[Db_Date], i._Position
INTO #inserted0;
SELECT [t].[Db_Date] FROM [Current_Moves] t
INNER JOIN #inserted0 i ON ([t].[Current_Nbr] = [i].[Current_Nbr]) AND ([t].[Db_Date] = [i].[Db_Date])
ORDER BY [i].[_Position];
',
N'#p0 nvarchar(450),#p1 nvarchar(4000),#p2 nvarchar(4000),#p3 nvarchar(4000)',
#p0=N'AAAAA',#p1=NULL,#p2=N'LOC_123',#p3=N'xxxxx'
I haven't actually fixed that error, but I was able to make it work by setting the DateTime column's value on C#, instead of expecting the database to do that.
Like another user, my problem is caused by a rowversion in SQL Server (called byte[] ChangeVersion in our model). Entity Framework was appending where ChangeVersion = ... as part of the SQL queries. However, the value Entity Framework used for the ChangeVersion was default (0). Entity Framework has decided that the ChangeVersion property should not be populated from the database with the following:
var deleteCompany = dbContext.Company.FirstOrDefault(x => x.CompanyId == cmvm.DeleteCompanyId.Value);
// at this point, deleteCompany.ChangeVersion = 0 but other fields are populated.
dbContext.Company.Remove(deleteCompany);
dbContext.SaveChanges(); // error expected 1 row but 0 affected
The model builder looks like
entity.Property(e => e.ChangeVersion).HasColumnName("ChangeVersion")
.IsRequired()
.IsRowVersion();
Changing the original lookup query to AsNoTracking fixes the issue. This works without error
// Call this AsNoTracking. Otherwise Entity Frameworks throws out the ChangeVersion for some reason.
var deleteCompany = dbContext.Company.AsNoTracking().FirstOrDefault(x => x.CompanyId == cmvm.DeleteCompanyId.Value);
dbContext.Entry(deleteCompany).State = EntityState.Deleted;
dbContext.Company.Remove(deleteCompany);
dbContext.SaveChanges();
I ran into this same problem with a SQLite database, but with updates instead of inserts. Calling SaveChangesAsync instead of SaveChanges was the solution.
For my case, I had updating 2 rows instead of 1.
I had less fields in PK group in entity building, than it was in DB..
entity.HasKey(e => new { e.field1, e field2, e.missedField3 }).HasName("My_Table_PK");
The code:
var stream=await this.oneDriveClient.Drive.Items[itemid].Content.Request().GetAsync();
Has been running fine for weeks but stopped working after the Onedrive update last night.
It is throwing exception 'Microsoft.Graph.ServiceException' when we try to download files using the API, file uploads still work. We are also getting the "ItemNotFound" error code.
Below is the exception message and stack trace.
ex.Message: Exception of type 'Microsoft.Graph.ServiceException' was thrown.
ex.StackTrace:
at Microsoft.Graph.HttpProvider.<SendAsync>d__19.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.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at Microsoft.Graph.BaseRequest.<SendRequestAsync>d__34.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.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at Microsoft.Graph.BaseRequest.<SendStreamRequestAsync>d__33.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.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at TMSPro.Shared_Objects.ucOneDriveBrowser.<btnDownload_Click>d__5f.MoveNext() in c:\Working\TMSPro_VS2012\TMSPro\Shared_Objects\ucOneDriveBrowser.cs:line 1083
The issue is with Authentication. This code seems to fix it:
var adalAuthProvider = new AdalAuthenticationProvider(
this.AadClientId,
this.AadReturnUrl);
this.oneDriveClient = new OneDriveClient(this.AadTargetUrl + "/_api/v2.0", adalAuthProvider, new HttpProvider(new HttpClientHandler { AllowAutoRedirect = true }, true));
authTask = adalAuthProvider.AuthenticateUserAsync(this.AadTargetUrl);
try
{
await authTask;
}
I'm experiencing exactly the same issue. When checking Fiddler, it seems that the response that is returned is a web page with the message: "Sorry something went wrong. Sorry you cannot access this document. ... Correlation ID: 072abf9d-7097-3000-a357-3f21c379dac7 ..."
The Microsoft.Graph.ServiceException has an error code: ItemNotFound.
This was working for ages, and now suddenly stopped working.
This was an issue in the OneDrive for Business service that has since been resolved. We apologize for the inconvenience, and have taken steps to minimize the chances of similar failures in the future.
I recently started a Microsoft Band application for Windows Phone 8.1.
The application basically uses UV sensors. But the problem here is not the UV, rather just sending the notification.
The code that sends the notification to the Band looks like (And where it goes to the exception):
await bandClient.NotificationManager.SendMessageAsync(tileGuid, "Title", "Body", DateTimeOffset.Now, MessageFlags.ShowDialog);
The full exception is:
(Exception parameter is below this question)
Handled = false
"Device status code: 0xA0D4000A received"
It is thrown from file App.g.i.cs:
#if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION
UnhandledException += (sender, e) =>
{
if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();
};
#endif
I searched the web for this exception, but no result.
Weird part is, that actually at one point this code worked and sent the notification.
It has also sent some exception about "Transport" and "Stream" something, but I cannot re-product those exceptions again right now.
I have done:
Factory reset the Band and reconnect (Unregister and stuff also).
Restart the phone and try other phones.
Moved the notification to be thrown later or earlier in code.
Does anyone happen to have any ideas or such, what could be done and what could be wrong
Exception parameter:
+ Exception {Microsoft.Band.BandOperationException: Device status code: 0xA0D4000A received.
at Microsoft.Band.BandClient.CheckStatus(CargoStatus status, CommandStatusHandling statusHandling)
at Microsoft.Band.BandClient.SendNotification[T](UInt16 notificationId, Guid& tileId, T& notificationInfo, PooledBuffer payload)
at Microsoft.Band.BandClient.SendMessage(Guid& tileId, String title, String body, DateTimeOffset timestamp, MessageFlags flags, CancellationToken token)
at Microsoft.Band.BandClient.<>c__DisplayClass11.<SendMessageAsync>b__10()
at System.Threading.Tasks.Task.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
--- 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.GetResult()
at Uvicorn.PivotPage.<ThrowNotification>d__26.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<ThrowAsync>b__3(Object state)
at System.Threading.WinRTSynchronizationContext.Invoker.InvokeCore()} System.Exception {Microsoft.Band.BandOperationException}
Make sure to verify that the Tile with the GUID passed to the SendMessageAsync() method has first been added to the Band (for example, after a factory reset).
Are you able to send a notification to the band not going through the tile? Just a vibrate notification? Those do not require the tile. I would like to rule out the tile as the issue.
This is a continuation from this question:
Multiple Task Continuation
I have changed my code as in the answer, however now I am receiving TaskCancelledExceptions when I try to run tasks.
public virtual async Task RunAsync(TaskWithProgress task)
{
Show();
TaskIsRunning();
await SetCompletedHandler(TaskComplete());
await SetCancelledHandler(TaskCancelled())
await SetFaultedHandler(TaskFaulted());
await task;
Close();
}
however the following code does not. I am a bit stuck as to why.
public virtual Task RunAsync(TaskWithProgress task)
{
Show();
TaskIsRunning();
SetCompletedHandler(TaskComplete());
SetCancelledHandler(TaskCancelled())
SetFaultedHandler(TaskFaulted());
return task;
}
The calling code basically involves the following:
await progressDialog.RunAsync(task);
Edit:
I do not cancel a cancellationtoken anywhere so I can't see why this is throwing that exception.
The three SetXXXHandler() methods basically perform the following code with different continuation status:
task.ContinueWith(_ => action(), CancellationToken.None, TaskContinuationOptions.OnlyOnCanceled, this.Scheduler);
The Stack trace is here:
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at FugroDXExt.frmBaseProgressAsync.<RunAsync>d__7.MoveNext() in d:\C#\FugroDXExt\trunk\frmBaseProgressAsync.cs:line 92
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at FCP.Forms.frmProcessing.<mnuApplyCenteredSmoothing_ItemClick>d__34.MoveNext() in d:\C#\FCP\FCP\Forms\frmProcessing.cs:line 578
Close() simply closes the form. If I remove that line the same thing occurs.
You say that SetCancelledHandler just adds a continuation to the task. I assume that's the same task RunAsync gets as a parameter although i can't tell by your code how SetCancelledHandler gets a task to continue on (I assume we're missing some code). Anyways...
You register 3 continuations on a task that will run when the task completes, is canceled and is faulted. Now let's assume the original task ran to completion successfully without being canceled. That means that 2 of your continuations (OnCanceled and OnFaulted) will not run because they don't need to be. The way to tell a task to not run in the TPL is to cancel it, and that happens automatically.
The difference between your 2 code snippets is that in the first one you await the task continuations, and they get canceled which explains your exception. On the second snippet you don't await the continuations, just the original task that successfully ran to completion.
P.S: I think the second option is more appropriate. You don't need to await all those continuations. You want to let them run if they need to.
TL;DR: You await a canceled continuation task. The continuation task, not the original, is the one that throws an exception.