Getting token from Office 365 throws 'unknown_error' - outlook

I'm following the following tutorial(Outlook dev center tutorial) and my code is throwing an unknown_error in this part (at the get the token):
public async Task<ActionResult> Authorize() {
// Get the 'code' parameter from the Azure redirect
string authCode = Request.Params["code"];
string authority = "https://login.microsoftonline.com/common";
string clientId = System.Configuration.ConfigurationManager.AppSettings["ida:ClientID"]; ;
string clientSecret = System.Configuration.ConfigurationManager.AppSettings["ida:ClientSecret"]; ;
AuthenticationContext authContext = new AuthenticationContext(authority);
// The same url we specified in the auth code request
Uri redirectUri = new Uri(Url.Action("Authorize", "Home", null, Request.Url.Scheme));
// Use client ID and secret to establish app identity
ClientCredential credential = new ClientCredential(clientId, clientSecret);
try {
// Get the token
var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(authCode, redirectUri, credential, scopes); <--- HERE
// Save the token in the session
Session["access_token"] = authResult.Token;
// Try to get user info
Session["user_email"] = GetUserEmail(authContext, clientId);
return Redirect(Url.Action("Inbox", "Home", null, Request.Url.Scheme));
} catch (AdalException ex) {
return Content(string.Format("ERROR retrieving token: {0}", ex.Message));
}
}
Stack trace:
at Microsoft.Experimental.IdentityModel.Clients.ActiveDirectory.AdalHttpClient.<GetResponseAsync>d__0`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.Experimental.IdentityModel.Clients.ActiveDirectory.AcquireTokenHandlerBase.<SendHttpMessageAsync>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.Experimental.IdentityModel.Clients.ActiveDirectory.AcquireTokenHandlerBase.<SendTokenRequestAsync>d__b.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.Experimental.IdentityModel.Clients.ActiveDirectory.AcquireTokenHandlerBase.<RunAsync>d__0.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.Experimental.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.<AcquireTokenByAuthorizationCodeCommonAsync>d__4a.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.Experimental.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.<AcquireTokenByAuthorizationCodeAsync>d__0.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 OutlookCSharp.Controllers.HomeController.<Authorize>d__3.MoveNext() in C:\\_DevLocal\\OutlookApi\\OutlookCSharp\\Controllers\\HomeController.cs:line 61
anyone knows what might be going wrong?

You can try this project , which already implemented the code from your referring url . And it can successfully login.
https://github.com/aukgit/Google-Outlook-Calender-Integrate/releases
There could be several things that could have gone wrong :
Probably you had missed to download the exact nuget packages
Install-Package Microsoft.Experimental.IdentityModel.Clients.ActiveDirectory -Version 4.0.208020147-alpha -Pre
Install-Package Microsoft.Office365.OutlookServices-V2.0
Probably app is not registered correctly with url.
Probably scopes are not given,

Related

ASP.NET identity with mysql instead of SQL Server null reference

I want to use the ASP.NET Web API to work with MySQL. I followed the steps described in:
https://learn.microsoft.com/en-us/aspnet/identity/overview/getting-started/aspnet-identity-using-mysql-storage-with-an-entityframework-mysql-provider
So what I did was the following:
Install the mysql connector and created a mysql database locally via workbench
Add the reference to mysql.data to the project
Via nuget manager the mysql.data.entity installed
The config did automatically added the mysql provider
Config:
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient"
type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="MySql.Data.MySqlClient"
type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.10.8.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d">
</provider>
</providers>
</entityFramework>
I added the class MySqlInitializer:
public class MySqlInitializer : IDatabaseInitializer<ApplicationDbContext>
{
public void InitializeDatabase(ApplicationDbContext context)
{
if (!context.Database.Exists())
{
// if database did not exist before - create it
context.Database.Create();
}
else
{
// query to check if MigrationHistory table is present in the database
var migrationHistoryTableExists = ((IObjectContextAdapter)context).ObjectContext.ExecuteStoreQuery<int>(
"SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'IdentityMySQLDatabase' AND table_name = '__MigrationHistory'");
// if MigrationHistory table is not there (which is the case first time we run) - create it
if (migrationHistoryTableExists.FirstOrDefault() == 0)
{
context.Database.Delete();
context.Database.Create();
}
}
}
}
I changed the ApplicationDbContext to:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
static ApplicationDbContext()
{
Database.SetInitializer(new MySqlInitializer());
}
public ApplicationDbContext()
: base("DefaultConnection")
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
My connection string is:
<connectionStrings>
<add name="DefaultConnection"
connectionString="Database=IdentityMySQLDatabase;Data Source=localhost;User Id=root;Password=Admin!##"
providerName="MySql.Data.MySqlClient" />
</connectionStrings>
I'm using advanced rest client to test the api. But when I want to register a new user I get a null reference. This is my stacktrace:
MySql.Data.MySqlClient.MySqlProviderServices.GetDbProviderManifestToken(DbConnection connection)
at System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection)
at System.Data.Entity.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices providerServices, DbConnection connection)
at System.Data.Entity.Infrastructure.DefaultManifestTokenResolver.<>c__DisplayClass1.b__0(Tuple3 k)
at System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func2 valueFactory)
at System.Data.Entity.Infrastructure.DefaultManifestTokenResolver.ResolveManifestToken(DbConnection connection)
at System.Data.Entity.Utilities.DbConnectionExtensions.GetProviderInfo(DbConnection connection, DbProviderManifest& providerManifest)
at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
at System.Data.Entity.Internal.RetryLazy2.GetValue(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.InternalContext.Initialize()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet1.Initialize() at
System.Data.Entity.Internal.Linq.InternalSet1.get_InternalContext()
at
System.Data.Entity.Infrastructure.DbQuery1.System.Linq.IQueryable.get_Provider()
at
System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync[TSource](IQueryable1
source, Expression1 predicate, CancellationToken cancellationToken)
at
System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync[TSource](IQueryable1
source, Expression1 predicate) at
Microsoft.AspNet.Identity.EntityFramework.UserStore6.d__67.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.AspNet.Identity.TaskExtensions.CultureAwaiter1.GetResult()
at
Microsoft.AspNet.Identity.UserValidator2.d__14.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.AspNet.Identity.UserValidator2.<ValidateAsync>d__13.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.AspNet.Identity.UserManager2.d__73.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.AspNet.Identity.UserManager2.<CreateAsync>d__79.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
TestMYSQL.Controllers.AccountController.d__20.MoveNext() in
D:\Visual Studio
Projects\Private\TestMYSQL\TestMYSQL\Controllers\AccountController.cs:line
333 --- 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.Threading.Tasks.TaskHelpersExtensions.d__1`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.Controllers.ApiControllerActionInvoker.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.Controllers.ActionFilterResult.d__5.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.Filters.AuthorizationFilterAttribute.d__3.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.Controllers.AuthenticationFilterResult.d__5.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.d__15.MoveNext()
Am I missing something? Any help would be appreciated. I have searched for a 2 days now and still no success of solving the issue.
Thanks.
After researching the possibilites. The solution was simpler then I thought. If someone, had the same problem here is what I did:
- Add new project mvc with identity for individual users login.
- Install nuget package Mysql.Data
- Install nuget package Mysql.Data.EntityFramework
- Create your own mysql database and get the connection string.
- Change the connection string and add the providername 'MySql.Data.MySqlClient'
Startup and register a username, the application creates a database in mysql for you.
I hope this well help someone who encountered the same problems.

ObjectDisposedException in ASP.NET Boilerplate manage services

I've decided to separate logic from RoleAppService to RoleService, because I need to use role methods in other app services. By separating logic I can avoid injecting endpoints to other endpoints (e.g. RoleAppService to UserAppService) and possible circular dependency. API is also not visible outside - that's why class inherit from AbpServiceBase, no ApplicationService (which make service visible in swagger). Unfortunately, when I try to use boilerplate manager classes (e.g. RoleManager, UserManager) inside RoleService method, following exception is thrown:
Cannot access a disposed object.
Object name: 'RoleManagerProxy'.
With stack trace:
at Microsoft.AspNetCore.Identity.RoleManager`1.ThrowIfDisposed()
at Microsoft.AspNetCore.Identity.RoleManager`1.FindByNameAsync(String roleName)
at Castle.Proxies.Invocations.RoleManager`1_FindByNameAsync.InvokeMethodOnTarget()
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Castle.Proxies.RoleManagerProxy.FindByNameAsync(String roleName)
at Abp.Authorization.Roles.AbpRoleManager`2.<CheckDuplicateRoleNameAsync>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.Authorization.Roles.AbpRoleManager`2.<UpdateAsync>d__42.MoveNext() in D:\Github\aspnetboilerplate\src\Abp.ZeroCore\Authorization\Roles\AbpRoleManager.cs:line 283
--- 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 System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at VZero.Roles.RoleService.<Create>d__6.MoveNext() in C:\Users\Marcin\source\repos\translink.vendorforum\Translink.Api\src\VZero.Application\Roles\RoleService.cs:line 42
--- 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 System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at VZero.Roles.RoleService.<CreateOtherDocumentUserRole>d__9.MoveNext() in C:\Users\Marcin\source\repos\translink.vendorforum\Translink.Api\src\VZero.Application\Roles\RoleService.cs:line 94
--- 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 System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at VZero.Roles.RoleService.<GetOtherDocumentRole>d__11.MoveNext() in C:\Users\Marcin\source\repos\translink.vendorforum\Translink.Api\src\VZero.Application\Roles\RoleService.cs:line 107
--- 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 System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at VZero.Roles.RoleService.<UpdateOtherDocumentUserRole>d__10.MoveNext() in C:\Users\Marcin\source\repos\translink.vendorforum\Translink.Api\src\VZero.Application\Roles\RoleService.cs:line 100
--- 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 System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at VZero.Users.UserAppService.<Update>d__20.MoveNext() in C:\Users\Marcin\source\repos\translink.vendorforum\Translink.Api\src\VZero.Application\Users\UserAppService.cs:line 226
--- 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.Threading.InternalAsyncHelper.<AwaitTaskWithPostActionAndFinallyAndGetResult>d__5`1.MoveNext() in D:\Github\aspnetboilerplate\src\Abp\Threading\InternalAsyncHelper.cs:line 120
--- 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 lambda_method(Closure , Object )
at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.AwaitableObjectResultExecutor.<Execute>d__0.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.<InvokeActionMethodAsync>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.<InvokeNextActionFilterAsync>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.<InvokeInnerFilterAsync>d__13.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.<InvokeNextExceptionFilterAsync>d__24.MoveNext()
Error seems to be related with framework configuration. I've tried to end service name with AppService, but it didn't help at all. Service is registered in Windsor Castle framework. What interesting - inside class properly works boilerplate repositories, like RoleRepository, UserReposistory - unfortunately RoleManager/UserManager not. Below is the fragment of the the class:
public class RoleService : AbpServiceBase, IRoleService
{
private readonly RoleManager _roleManager;
private readonly IRepository<Role> _roleRepository;
private readonly UserManager _userManager;
private readonly IRepository<User, long> _userRepository;
private readonly IPermissionManager _permissionManager;
public RoleService(RoleManager roleManager, IRepository<Role> roleRepository,
UserManager userManager, IRepository<User, long> userRepository,
IPermissionManager permissionManager)
{
_roleManager = roleManager;
_roleRepository = roleRepository;
_userManager = userManager;
_userRepository = userRepository;
_permissionManager = permissionManager;
}
public async Task<RoleDto> Create(CreateRoleDto createRoleDto, Action<IdentityResult> checkErrorsMethod)
{
var role = ObjectMapper.Map<Role>(createRoleDto);
role.SetNormalizedName();
await _roleManager.UpdateAsync(role); // here exception is thrown
var grantedPermissions = _permissionManager
.GetAllPermissions()
.Where(p => createRoleDto.Permissions.Contains(p.Name))
.ToList();
await _roleManager.SetGrantedPermissionsAsync(role, grantedPermissions);
return role.MapTo<RoleDto>();
}
I would be so grateful for any help.
If you add [UnitOfWork] attribute, don't forget to make method public virtual

EF Core: An exception occurred in the database while iterating the results of a query

I'm getting this error from my web app hosted in Azure. It runs ok for a few days and then suddenly stops working.
Is there an issue with the connection perhaps? Which object reference does not have an instance?
YYYY-MM-DD hh:mm:ss [Error] An exception occurred in the database while iterating the results of a query.
System.NullReferenceException: Object reference not set to an instance of an object. at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable.AsyncEnumerator.<BufferAllAsync>d__12.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 Microsoft.EntityFrameworkCore.Query.RelationalQueryContext.<RegisterValueBufferCursorAsync>d__14.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 Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable.AsyncEnumerator.<BufferlessMoveNext>d__9.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 Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable.AsyncEnumerator.<MoveNext>d__8.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.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.SelectAsyncEnumerable`2.SelectAsyncEnumerator.<MoveNext>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 System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.<_FirstOrDefault>d__82`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.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at Microsoft.EntityFrameworkCore.Query.Internal.TaskResultAsyncEnumerable`1.Enumerator.<MoveNext>d__3.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 Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.SelectAsyncEnumerable`2.SelectAsyncEnumerator.<MoveNext>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 System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.<MoveNext>d__5.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 MyProject.Data.SectionRepository.<GetByTypePathAndAlias>d__6.MoveNext() in /Users/webaccount/myproject/src/MyProject.Data/Repositories/SectionRepository.cs:line 34
There's nothing special about my repository or entity code.
public async Task<Section> GetByTypeId(string typeId)
{
var sections = from s in this.DbContext.Sections
where s.TypeId == typeId
select s;
return await sections.FirstOrDefaultAsync(); // <-- LINE 34
}
This is my entity.
public class Section
{
[Key]
public int Id { get; set; }
public DateTimeOffset CreatedDate { get; set; }
public string TypeId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
Is it related to this perhaps? https://github.com/aspnet/EntityFrameworkCore/issues/8026
Will it help if I convert my repository methods to sync and staying async at the Controller?
It runs ok for a few days and then suddenly stops working.
Object reference not set to an instance of an object
Firstly, you can try to remote debug your web app and check the this.DbContext.
Secondly, you can create/use a context instance per request, and this artciel shows some general guidelines when deciding on the lifetime of the context, you can check it.

Operation is not valid due to the current state of the object

An error has occurred.
Operation is not valid due to the current state of the object.
System.InvalidOperationException
at
Microsoft.Bot.Builder.Dialogs.Conversation.<>c__31.<ResumeAsync>b__3_0()
at
Microsoft.Bot.Builder.Dialogs.Internals.ReactiveDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__31.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.Bot.Builder.Dialogs.Internals.ScoringDialogTask1.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__31.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.Bot.Builder.Dialogs.Internals.PersistentDialogTask.d__31.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
Microsoft.Bot.Builder.Dialogs.Internals.PersistentDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__31.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.Bot.Builder.Dialogs.Internals.SerializingDialogTask.d__41.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.Bot.Builder.Dialogs.Internals.ExceptionTranslationDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__21.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.Bot.Builder.Dialogs.Internals.LocalizedDialogTask.d__21.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.Bot.Builder.Dialogs.Internals.PostUnhandledExceptionToUserTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__51.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
Microsoft.Bot.Builder.Dialogs.Internals.PostUnhandledExceptionToUserTask.d__51.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.Bot.Builder.Dialogs.Internals.LogPostToBot.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__31.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.Bot.Builder.Dialogs.Conversation.d__51.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.Bot.Builder.Dialogs.Conversation.<ResumeAsync>d__31.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
BotApplication.Controllers.OAuthCallbackController.d__0.MoveNext()
in
C:\BotApplication\BotApplication\Controllers\OAuthCallbackController.cs:line
55 --- 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.Threading.Tasks.TaskHelpersExtensions.d__3`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.Controllers.ApiControllerActionInvoker.d__0.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.Controllers.ActionFilterResult.d__2.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.d__1.MoveNext()
This is happening when i'm trying to resume a conversation after user authentication.
I call authentication this way :
In my first dialog :
var message = context.MakeMessage();
await context.Forward(new SecondDialog(), HandleOptions, message, CancellationToken.None);
Then in my SecondDialog have this :
var message = await argument;
MyStaticModel.toId = message.From.Id;
MyStaticModel.toName = message.From.Name;
MyStaticModel.fromId = message.Recipient.Id;
MyStaticModel.fromName = message.Recipient.Name;
MyStaticModel.serviceUrl = message.ServiceUrl;
MyStaticModel.channelId = message.ChannelId;
MyStaticModel.conversationId = message.Conversation.Id;
await context.Forward(new SimpleFacebookAuthDialog(message), ResumeAfterLogIn, message, CancellationToken.None);
In my Facebook Dialog i make resumption cookie this way :
public SimpleFacebookAuthDialog(IMessageActivity msg)
{
ResumptionCookie = new ResumptionCookie(msg);
}
And when user authenticate i handle authentication :
public async Task<HttpResponseMessage> OAuthCallback([FromUri] string userId, [FromUri] string botId, [FromUri] string conversationId, [FromUri] string channelId, [FromUri] string serviceUrl, [FromUri] string locale, [FromUri] string code, [FromUri] string state, CancellationToken token)
{
//Get the resumption cookie
Address address = new Address
(
// purposefully using named arguments because these all have the same type
botId: FacebookHelpers.TokenDecoder(botId),
channelId: channelId,
userId: FacebookHelpers.TokenDecoder(userId),
conversationId: FacebookHelpers.TokenDecoder(conversationId),
serviceUrl: FacebookHelpers.TokenDecoder(serviceUrl)
);
//var resumptionCookie = new ResumptionCookie(FacebookHelpers.TokenDecoder(userId), FacebookHelpers.TokenDecoder(botId), FacebookHelpers.TokenDecoder(conversationId), channelId, FacebookHelpers.TokenDecoder(serviceUrl), locale: locale);
var resumptionCookie = new ResumptionCookie(address, userName: null, isGroup: false, locale: locale);
// Exchange the Facebook Auth code with Access token
var accessToken = await FacebookHelpers.ExchangeCodeForAccessToken(resumptionCookie, code, SimpleFacebookAuthDialog.FacebookOauthCallback.ToString());
// Create the message that is send to conversation to resume the login flow
var msg = resumptionCookie.GetMessage();
msg.Text = $"token:{accessToken.AccessToken}";
// Resume the conversation to SimpleFacebookAuthDialog
await Conversation.ResumeAsync(resumptionCookie, msg, CancellationToken.None);
It falls on the last line of code. When Resuming conversation.
Any help ?
I got the same error when I run tests in vs 2019.
I could solve this by cleaning the solution ,closing vs and deleting temp files anf re launching vs-2019.
I followed the link https://developercommunity.visualstudio.com/content/problem/875545/xunit-test-net-core-project-with-vs-2019-is-throwi.html
I fix this guys.
I don't know what the real reason is, but when i used to await for argument and store it as a message, later, parameters were wrong in resumption cookie.
Now, i cast argument as activity :
var message = (Activity)context.Activity;
And it works properly.
Problem solved :)
I got this error message when attempting to display adaptive cards. It turned out I had added the json files to the solution as content and not as embedded resources. After switching them to be embedded resources they displayed fine.

Web API CORS OPTION returns 500 randomly only on azure

Im developing a .NET Web Api (using OWIN) and a ember app consuming the web api. The web api is hosted on azure (api app). The problem is that sometimes the option call is failing (500 error) and the gui hangs. If I triggers the option call again it works again. If Im running the api on my local IIS, this problem never happens. The problem occurs most often when I have not done anything/triggered any ajax calls in the web app for awhile (5 min). Any clue why this is happening?
This is my startup config:
public partial class
Startup
{
public void Configuration(IAppBuilder app)
{
//enable cors
app.UseCors(CorsOptions.AllowAll);
//enable hangfire
Hangfire.GlobalConfiguration.Configuration
.UseSqlServerStorage("DbConnection")
.UseActivator(new StructureMapJobActivator(IoC.Initialize()));
app.UseHangfireDashboard();
app.UseHangfireServer();
//automapper
AutoMapperBootstrapper.Bootstrap();
//oauth 2
var userManager = new UserManager();
var authConfig = new SentinelAuthorizationServerOptions()
{
UserManager = userManager,
ClientManager = new ClientManager(),
};
var shaProvider = new SHA2CryptoProvider();
var onBoardTokenRepository = new OnBoardTokenRepository(new ConnectionFactory(new Configuration()), "DbConnection");
authConfig.TokenManager = new TokenManager(LogManager.GetLogger<Startup>(), userManager, new PrincipalProvider(shaProvider), shaProvider, new TokenFactory(), onBoardTokenRepository);
app.UseSentinelAuthorizationServer(authConfig);
GlobalConfiguration.Configure(WebApiConfig.Register);
}
I found this error in the azure event log:
https://microsoft-apiapp08044e6364624e2e88cfda954ace012a.azurewebsites.net:443/job/getemployerjobs/job/getemployerjobs104.45.82.120FalseIIS APPPOOL\Microsoft-ApiApp08044e6364624e2e88cfda954ace012a108IIS APPPOOL\Microsoft-ApiApp08044e6364624e2e88cfda954ace012aFalse at System.Web.HttpHeaderCollection.SetHeader(String name, String value, Boolean replace)
at System.Web.HttpHeaderCollection.Set(String name, String value)
at Microsoft.Owin.Host.SystemWeb.CallHeaders.AspNetResponseHeaders.Set(String key, String[] values)
at Microsoft.Owin.Host.SystemWeb.CallHeaders.AspNetResponseHeaders.set_Item(String key, String[] value)
at Microsoft.Owin.Infrastructure.OwinHelpers.SetHeaderUnmodified(IDictionary`2 headers, String key, String[] values)
at Microsoft.Owin.Infrastructure.OwinHelpers.AppendHeaderUnmodified(IDictionary`2 headers, String key, String[] values)
at Microsoft.Owin.HeaderDictionary.AppendValues(String key, String[] values)
at Microsoft.Owin.Security.OAuth.OAuthBearerAuthenticationProvider.<.ctor>b__2(OAuthChallengeContext context)
at Microsoft.Owin.Security.OAuth.OAuthBearerAuthenticationProvider.ApplyChallenge(OAuthChallengeContext context)
at Microsoft.Owin.Security.OAuth.OAuthBearerAuthenticationHandler.ApplyResponseChallengeAsync()
at Microsoft.Owin.Security.Infrastructure.AuthenticationHandler.<ApplyResponseCoreAsync>d__b.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.Owin.Security.Infrastructure.AuthenticationHandler.<ApplyResponseAsync>d__8.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.Owin.Security.Infrastructure.AuthenticationHandler.<TeardownAsync>d__5.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.Owin.Security.Infrastructure.AuthenticationMiddleware`1.<Invoke>d__0.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.Owin.Security.Infrastructure.AuthenticationMiddleware`1.<Invoke>d__0.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.Owin.Mapping.MapMiddleware.<Invoke>d__0.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.Owin.Cors.CorsMiddleware.<Invoke>d__0.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.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContextStage.<RunApp>d__5.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.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.<DoFinalWork>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar)
at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar)
at System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
It seems this is related to Microsofts OWIN implementation: http://katanaproject.codeplex.com/discussions/540202 .
The relevant pull request is here: https://katanaproject.codeplex.com/workitem/263
The underlying OWIN OAuth middleware sometimes "seals off" the response when it creates a response.

Resources