sarpay
10/11/2018 - 11:38 AM

ABP

Data Filters

https://aspnetboilerplate.com/Pages/Documents/Data-Filters

using Abp.Domain.Uow;

namespace Echonos.Relationships
{
  public class RelationshipsAppService
  {
    private readonly IUnitOfWorkManager _unitOfWorkManager;
    ...
    
    public RelationshipsAppService(IUnitOfWorkManager unitOfWorkManager)
    {
      _unitOfWorkManager = unitOfWorkManager;
      ...
    }
    
    public async Task<int<SomeDto>> GetAllOrganizations(GetAllForLookupTableInput input)
    {
      // Disable IMayHaveTenant
      using (_unitOfWorkManager.Current.DisableFilter(AbpDataFilters.MayHaveTenant))
      {
        ...
      }
      // Disable Soft-Delete
      using (_unitOfWorkManager.Current.DisableFilter(AbpDataFilters.SoftDelete))
      {
        ...
      }
    }
  }
}

AsyncHelper

var paymentsList = AsyncHelper.RunSync(() => _tahsilatServiceManager.GetInstallments(policy));
var installmentsList = paymentsList
    .FirstOrDefault(x => x.Code == policy.PaymentCode && x.IsSelected.Equals(true))
    ?.Installments;

IoC Containers

var productAppService = IocManager.Instance.Resolve<IProductAppService>();
var q = from t in productAppService.GetAllPlan()
where t.ProductId == productId && t.IsApproved
select
new
{
id = t.Id,
text = t.Code + " - " + t.Name
};
IocManager.Instance.Release(productAppService);

Cache Manager

private readonly ICacheManager _cacheManager;

public async Task<List<Musteri>> GetAllNetworkCorpCustomersFromCacheAsync()
{
const string cacheName = "AllNetworkCorpCustomers";
var iCache = _cacheManager.GetCache(cacheName);
//iCache.Clear(); // Clears the cache
return await iCache.Get(cacheName, async () => await GetAllNetworkCorpCustomersAsync());
}

Authentication

// SERVICE (REDIRECTS TO LOGIN SCREEN)
[AbpAuthorize]
public class SessionAppService : HealthAppServiceBase, ISessionAppService
{
}

// CONTROLLER (REDIRECTS TO LOGIN SCREEN)
[AbpMvcAuthorize]
public class PolicyController : HealthControllerBase
{
}

// METHOD
[AbpAllowAnonymous]
public async Task<ActionResult> GetPlansByProductId(string id) {

}

// METHOD
[AbpMvcAuthorize(PermissionNames.ProductGroupDiscount)]
[HttpDelete]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Delete(string[] ids) {


}

if (PermissionChecker.IsGranted(PermissionNames.ProductRuleEngineSettings))
{
}

//javascript
if (!abp.auth.isGranted("App.Policy.ViewCoverageDetail")) {
bindNoAccessTooltip($(".view-coverage"), "Prim Görüntülemeye Yetkiniz Bulunmamaktadır.");
}

USER INFO

var currentUserIdentifier = AbpSession.ToUserIdentifier();
var currentUserTenantId = currentUserIdentifier.TenantId;
var userId = AbpSession.UserId.HasValue ? (int)AbpSession.UserId : 0
private readonly ISessionAppService _sessionAppService;

var loginInformation = AsyncHelper.RunSync(() => _sessionAppService.GetCurrentLoginInformations());
var UserId = loginInformation.User.Id;
var UserName = loginInformation.User.UserName;
var AgentCode = loginInformation.User.DefaultAgentCode;
var BranchCode = loginInformation.User.DefaultBranchCode.GetValueOrDefault();
var SourceCode = loginInformation.User.DefaultSourceCode.GetValueOrDefault();
var userAuthAuthority = loginInformation.User.UserAuthAuthority;
var userAuthLevel = loginInformation.User.UserAuthLevel;
var userAuthProfile = loginInformation.User.UserAuthProfile; // eg: "ACN"

DB Context Provider

private readonly IDbContextProvider<HealthDbContext> _dbContextProvider;

public PolicyRepository(
  IDbContextProvider<HealthDbContext> dbContextProvider
) : base(dbContextProvider)
{
  _dbContextProvider = dbContextProvider;
}

public async Task<long> GetSbmSagmerNoAsync(long policyNo)
{
  var db = _dbContextProvider.GetDbContext().Database;

  string sql = @"SELECT p.SBM_SAGMER_NO FROM sgl.POLICY p 
                WHERE p.POLICY_NO={0} AND p.ENDORSEMENT_NO=0 AND p.PROPOSAL_STATUS=1 AND p.POLICY_STATUS=7";

  sql = string.Format(sql, policyNo);
  var retval = await db.SqlQuery<long?>(sql).FirstOrDefaultAsync();

  return retval ?? 0;
}

public async Task<Policy> GetIncrementalPolicyAsync(long policyNo, string requestedEndorsementType, DateTime? untilDate)
{
  foreach (var p in allPoliciesByNoList)
  {
      if (p.EndorsementNo == 0)
      {
        _dbContextProvider.GetDbContext().Entry(p).State = EntityState.Detached;
        policy = p;
      }
  }
}

Unit of Work

https://aspnetboilerplate.com/Pages/Documents/Unit-Of-Work

The repository and unit of work patterns are intended to create an abstraction layer between the data access layer and the business logic layer of an application. The unit of work class coordinates the work of multiple repositories by creating a single database context class shared by all of them.

ABP automatically equips all controller, service and repository methods with UnitOfWork, without the need for manually adding the [UnitOfWork] attribute above the method declaration.

To Manually Trigger

UnitOfWorkManager.Current.SaveChanges();

// or
await UnitOfWorkManager.Current.SaveChangesAsync();

// or
CurrentUnitOfWork.SaveChanges();

//or
private readonly IUnitOfWorkManager _unitOfWorkManager;
await _unitOfWorkManager.Current.SaveChangesAsync();

To Disable

[UnitOfWork(IsDisabled = true)]

Dispose of the UnitOfWorkManager

private readonly IUnitOfWorkManager _unitOfWorkManager;
((IDisposable)_unitOfWorkManager.Current).Dispose();

Extend Transaction Timeout

var unitOfWorkOptions = new UnitOfWorkOptions
{
  Timeout = new TimeSpan(0, 0, 30, 0),
  IsTransactional = false,
  Scope = TransactionScopeOption.RequiresNew
};
using (var unitOfWork = _unitOfWorkManager.Begin(unitOfWorkOptions))
{
  var policyMessages = _policyManager
      .PrepNotificationMessagesForRenewalGuarantee(renewalCondition).Result;
  foreach (var pm in policyMessages)
  {
    sendResponse = _messagingManager.SendMessageFromTemplate(pm).Result;
  }
}

Class with Auditing (creates the necessary props / table columns for full auditing) :

using Abp.Domain.Entities.Auditing;

namespace Health.Products
{
  public class AgencyProductAuth : FullAuditedEntity
  {
    
  }
}
/*
  https://aspnetboilerplate.com/Pages/Documents/Logging
  
  Created Log.txt file is located under
  \Health.Web\App_Data\Logs
*/

using Castle.Core.Logging;

public class PolicyManager : DomainService, IPolicyManager
{
  public ILogger Logger { get; set; }
  
  public PolicyManager() {
    Logger = NullLogger.Instance;
  }

  public async Task<bool> CalculatePremium(Policy policy, PolicyInsured policyInsured)
  {
    if (policyInsured.PlanId == 66217)
    {
      Logger.Info(insured.ToJsonString());
    }
  }
}