Base solution for your next web application

Activities of "Healthbit"

I am using multiple db contexts. I am getting following error when I run existing unit tests: [24/06/2019 02:16:18 PM Informational] [xUnit.net 00:00:00.00] xUnit.net VSTest Adapter v2.4.1 (64-bit .NET Core 4.6.27617.05) [24/06/2019 02:16:19 PM Informational] [xUnit.net 00:00:00.88] Starting: XXXXDemo.Tests [24/06/2019 02:16:23 PM Error] [xUnit.net 00:00:04.40] XXXXDemo.Tests.Features.Features_Tests.Should_Not_Create_User_More_Than_Allowed_Count [FAIL] [24/06/2019 02:16:23 PM Informational] [xUnit.net 00:00:04.40] Microsoft.Data.Sqlite.SqliteException : SQLite Error 1: 'no such table: AbpEditions'.

** How to setup existing unit tests project and use different db contexts?**

@ismcagdas even all the default tests are not woking. All tests are ending with Microsoft.Data.Sqlite.SqliteException : SQLite Error 1: 'no such table: xxxx'.

CommerceDbContext.cs

using Abp.IdentityServer4;
using Abp.Zero.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using CommerceDemo.Authorization.Roles;
using CommerceDemo.Authorization.Users;
using CommerceDemo.Chat;
using CommerceDemo.Editions;
using CommerceDemo.Friendships;
using CommerceDemo.MultiTenancy;
using CommerceDemo.MultiTenancy.Accounting;
using CommerceDemo.MultiTenancy.Payments;
using CommerceDemo.Storage;

namespace CommerceDemo.EntityFrameworkCore
{
    public class CommerceDbContext : AbpZeroDbContext<Tenant, Role, User, CommerceDbContext>, IAbpPersistedGrantDbContext
    {
        /* Define an IDbSet for each entity of the application */

        public virtual DbSet<CommerceDemo.Main.Items.Item> Items { get; set; }
 


		public virtual DbSet<PersistedGrantEntity> PersistedGrants { get; set; }
        public CommerceDbContext(DbContextOptions<CommerceDbContext> options)
            : base(options)
        {
            
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

             
            modelBuilder.ConfigurePersistedGrantEntity();
        }
    }
}

ItemAppService_Tests.cs

using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Abp;
using Abp.Application.Services.Dto;
using Abp.Localization;
using CommerceDemo.Main.Items;
using CommerceDemo.Localization;
using CommerceDemo.Localization.Dto;
using CommerceDemo.Migrations.Seed.Host;
using CommerceDemo.Test.Base;
using Shouldly;
using Xunit;

namespace CommerceDemo.Tests.Main.Items
{
    // ReSharper disable once InconsistentNaming
    public class ItemAppService_Tests : AppTestBase
    {
        private readonly IItemAppService _ItemAppService;
        private readonly bool _multiTenancyEnabled  = CommerceDemoConsts.MultiTenancyEnabled;

        public ItemAppService_Tests()
        {
            if (_multiTenancyEnabled)
            {
                LoginAsHostAdmin();
            }
            else
            {
                LoginAsDefaultTenantAdmin();
            }

			_ItemAppService = Resolve<IItemAppService>();
 
        }

        [Fact]
        public async Task Test_GetItems()
        {
            //Act
            var output = await _ItemAppService.GetItems( new CommerceDemo.Main.Items.Dto.GetItemsInput());

            //Assert
            output.Items.Count.ShouldBeGreaterThan(0); ;
        }

    
    }
}

Hi,

We need to enable OAuth 2.0 for API. We need to give API access to third party and they should be accessign our API using OAuth 2.0.

Can you please briefly let us know what we need to do?

Thanks

Hi,

Thank you for reply. We are using ASP.NET Core & Angular.

I have multiple dbContexts. I want to retrieve data from two databases with a single query. I am getting following exception:

System InvalidOperationException: **Cannot use multiple DbContext instances within a single query execution. Ensure the query uses a single context instance.** at Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.Internal.ParameterExtractingExpressionVisitor.ValidateQueryProvider(IQueryable queryable) at Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.Internal.ParameterExtractingExpressionVisitor.EvaluateQueryable(Expression expression) at Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.Internal.ParameterExtractingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression) at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor) at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node) at System.Linq.Expressions.ExpressionVisitor.VisitLambda[T](Expression1 node) at Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.Internal.ParameterExtractingExpressionVisitor.VisitLambda[T](Expression1 node) at System.Linq.Expressions.Expression1.Accept(ExpressionVisitor visitor) at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node) at System.Linq.Expressions.ExpressionVisitor.VisitUnary(UnaryExpression node) at Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.Internal.ParameterExtractingExpressionVisitor.VisitUnary(UnaryExpression unaryExpression) at System.Linq.Expressions.UnaryExpression.Accept(ExpressionVisitor visitor) at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node) at System.Dynamic.Utils.ExpressionVisitorUtils.VisitArguments(ExpressionVisitor visitor, IArgumentProvider nodes) at System.Linq.Expressions.ExpressionVisitor.VisitMethodCall(MethodCallExpression node) at Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.Internal.ParameterExtractingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression) at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor.... `

Is there any workaround for this issue?

Hi,

Can you please have a look and see if you can help with my following code failing?

` private async Task ScheduleBroadcastMessageJob(CreateOrUpdateBroadcastMessageInput input, string broadcastMessageId) {

        var currentTicks = DateTime.Now.Ticks;
        var scheduleTicks = input.ScheduleDateTime.Value.Ticks;
        TimeSpan scheduleTime;
        if (input.SendType == BroadcastSendType.Schedule)
            scheduleTime = TimeSpan.FromTicks(scheduleTicks - currentTicks);
        else
            scheduleTime = new TimeSpan(0, 0, 30);
        await BackgroundJobManager.EnqueueAsync<BroadcastMessageJob, BroadcastMessageJobArgs>(new BroadcastMessageJobArgs
        {
            MessageInput = input,
            BroadcastMessageId = broadcastMessageId
        }, BackgroundJobPriority.Normal, scheduleTime);
        
    }`

Error Log

Failed Can not change the state to 'Enqueued': target method was not found.

System.TypeLoadException Could not load type 'HB.IQ.Main.Broadcast.BroadcastMessageJob' from assembly 'HB.IQ.Application, Version=7.2.0.0, Culture=neutral, PublicKeyToken=null'.

System.TypeLoadException: Could not load type 'HB.IQ.Main.Broadcast.BroadcastMessageJob' from assembly 'HB.IQ.Application, Version=7.2.0.0, Culture=neutral, PublicKeyToken=null'. at System.Reflection.RuntimeAssembly.GetType(RuntimeAssembly assembly, String name, Boolean throwOnError, Boolean ignoreCase, ObjectHandleOnStack type, ObjectHandleOnStack keepAlive) at System.Reflection.RuntimeAssembly.GetType(String name, Boolean throwOnError, Boolean ignoreCase) at System.TypeNameParser.ResolveType(Assembly assembly, String[] names, Func4 typeResolver, Boolean throwOnError, Boolean ignoreCase, StackCrawlMark& stackMark) at System.TypeNameParser.ConstructType(Func2 assemblyResolver, Func4 typeResolver, Boolean throwOnError, Boolean ignoreCase, StackCrawlMark& stackMark) at System.TypeNameParser.GetType(String typeName, Func2 assemblyResolver, Func4 typeResolver, Boolean throwOnError, Boolean ignoreCase, StackCrawlMark& stackMark) at System.Type.GetType(String typeName, Func2 assemblyResolver, Func`4 typeResolver, Boolean throwOnError) at Hangfire.Common.TypeHelper.DefaultTypeResolver(String typeName) at Hangfire.Storage.InvocationData.DeserializeJob()

Thanks.

One point i missed was that it works fine if i don't provide this "BackgroundJobPriority.Normal, scheduleTime)"

Its actually quite simple re-produce.

BackgroundJobManager.EnqueueAsync's Job which works would stop working if the delay timestamp is provided.

Thanks for your reply. Got it fixed. There were two HangFire Services was running for two difference branches of the projects. As soon as we stopped all services but one everything start working.

We are using ASP.NET Core Angular solution.  Our clients want to use our API. So we only want provide client_id and secret  to our clients instead of login and password. How can we enable Client Credentials Flow for identity server?

**I want hide endpoints from Swagger UI according to their permissions and features. I have tried https://support.aspnetzero.com/QA/Questions/4380 code. It works fine for host user but getting following exception when tanent loggedin: **

ObjectDisposedException: Cannot access a disposed object. Object name: 'UserManagerProxy'. Microsoft.AspNetCore.Identity.UserManager.ThrowIfDisposed() Microsoft.AspNetCore.Identity.UserManager.FindByIdAsync(string userId) Castle.Proxies.Invocations.UserManager1_FindByIdAsync.InvokeMethodOnTarget() Castle.DynamicProxy.AbstractInvocation.Proceed() Castle.DynamicProxy.AbstractInvocation.Proceed() Castle.Proxies.UserManagerProxy.FindByIdAsync(string userId) Abp.Authorization.Users.AbpUserManager<TRole, TUser>+<>c__DisplayClass70_0+<<GetUserPermissionCacheItemAsync>b__0>d.MoveNext() in AbpUserManager.cs Abp.Runtime.Caching.CacheExtensions+<>c__DisplayClass9_0<TKey, TValue>+<<GetAsync>b__0>d.MoveNext() Abp.Runtime.Caching.CacheBase.GetAsync(string key, Func<string, Task<object>> factory) in CacheBase.cs Abp.Runtime.Caching.CacheExtensions.GetAsync<TKey, TValue>(ICache cache, TKey key, Func<TKey, Task<TValue>> factory) in CacheExtensions.cs Abp.Authorization.Users.AbpUserManager<TRole, TUser>.GetUserPermissionCacheItemAsync(long userId) in AbpUserManager.cs Abp.Authorization.Users.AbpUserManager<TRole, TUser>.IsGrantedAsync(long userId, Permission permission) in AbpUserManager.cs Abp.Authorization.Users.AbpUserManager<TRole, TUser>.IsGrantedAsync(long userId, string permissionName) in AbpUserManager.cs Abp.Authorization.PermissionChecker<TRole, TUser>.IsGrantedAsync(long userId, string permissionName) in PermissionChecker.cs Abp.Authorization.PermissionChecker<TRole, TUser>.IsGrantedAsync(string permissionName) in PermissionChecker.cs Nito.AsyncEx.Synchronous.TaskExtensions.WaitAndUnwrapException<TResult>(Task<TResult> task) System.Threading.Tasks.ContinuationResultTaskFromResultTask<TAntecedentResult, TResult>.InnerInvoke() System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, object state) System.Threading.Tasks.Task.ExecuteWithThreadLocal(ref Task currentTaskSlot) Nito.AsyncEx.Synchronous.TaskExtensions.WaitAndUnwrapException<TResult>(Task<TResult> task) Nito.AsyncEx.AsyncContext.Run<TResult>(Func<Task<TResult>> action) HB.IQ.Web.Swagger.SwaggerAbpAuthorizeAttributeAuthorizationFilter.IsForbiddenDuePermissions(IEnumerable<AbpAuthorizeAttribute> attributes) in SwaggerAbpAuthorizeAttributeAuthorizationFilter.cs+ ` if (authorizeAttributes.Count != 0) foreach (var authorizeAttribute in authorizeAttributes) permissions.AddRange(authorizeAttribute.Permissions.ToList()); else return true; foreach (var permission in permissions) { var allow = _permissionChecker.IsGranted(permission); if (allow) return false; }``

HB.IQ.Web.Swagger.SwaggerAbpAuthorizeAttributeAuthorizationFilter.Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context) in SwaggerOperationIdFilter.cs +if (actionAbpAuthorizeAttributes.Count > 0) authAttributes = actionAbpAuthorizeAttributes; else if (controllerAbpAuthorizeAttributes.Count > 0) authAttributes = controllerAbpAuthorizeAttributes; // check if this action should be visible var forbiddenDuePermissions = IsForbiddenDuePermissions(authAttributes); if (!forbiddenDuePermissions) continue; // user passed all permissions checks // remove method or entire path (if there are no more methods in this path) switch (description.HttpMethod) Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GetSwagger(string documentName, string host, string basePath, string[] schemes) Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider) Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext) Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext) Microsoft.AspNetCore.Builder.Extensions.MapMiddleware.Invoke(HttpContext context) Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext) Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.Invoke(HttpContext context) Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context) IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext context, IEndpointRouter router, IUserSession session, IEventService events) in IdentityServerMiddleware.cs IdentityServer4.Hosting.MutualTlsTokenEndpointMiddleware.Invoke(HttpContext context, IAuthenticationSchemeProvider schemes) in MtlsTokenEndpointMiddleware.cs Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) IdentityServer4.Hosting.BaseUrlMiddleware.Invoke(HttpContext context) in BaseUrlMiddleware.cs Abp.AspNetZeroCore.Web.Authentication.JwtBearer.JwtTokenMiddleware+<>c__DisplayClass0_0+<b__0>d.MoveNext() Abp.AspNetZeroCore.Web.Authentication.JwtBearer.JwtTokenMiddleware+<>c__DisplayClass0_0+<b__0>d.MoveNext() Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Showing 1 to 10 of 12 entries