在園子吸收營養10多年,一直沒有貢獻,目前園子危機時刻,除了捐款+會員,也鼓起勇氣,發篇文助力一下。
2018年下半年,公司決定開發一款SaaS版行業供應鏈管理系統,經過選型,確定採用ABP(ASP.NET Boilerplate)框架。為了加快開發效率,購買了商業版的 ASP.NET ZERO(以下簡稱ZERO),選擇ASP.NET Core + Angular的SPA框架進行系統開發(ABP.IO屆時剛剛起步,還很不成熟,因此沒有選用)。
關於ABP與ZERO,園子裡已經有諸多介紹,因此不再贅述。本文側重介紹我們基於ZERO框架開發系統過程中進行的一些優化、調整、擴充套件部分的內容,方便有需要的園友們瞭解或者參考。
系統在2020年7月釋出上線(部署在阿里雲上),目前有超過500家企業/個人註冊體驗(付費的很少),感興趣的可以在此係統的著陸網站 scm.plus 註冊一個免費賬號體驗一下,歡迎大家的批評指正。
ZERO框架總體上來說還是不錯的,可以快速的上手,整合的通用功能(版本、租戶、角色、使用者、設定等)初期都可以直接使用,但還達不到直接釋出使用的水準,需要經過諸多的優化調整擴充套件後才能釋出上線。
基於系統功能定位,移除的這些不需要的功能,使系統儘可能的精簡。
在我們的開發環境內,經過測試與驗證,使用mysql資料庫時候,可以安全移除add-migration時候生成的龐大的Designer.cs檔案。移除Designer.cs檔案時候,需要把該檔案內的DbContext與Migration宣告語句移到對應的migration.cs檔案內:
[DbContext(typeof(SCMDbContext))]
[Migration("20230811015119_Upgraded_To_Abp_8_3")]
public partial class Upgraded_To_Abp_8_3 : Migration
{
...
}
[HttpPost]
[AbpMvcAuthorize(AppPermissions.Pages_Txxxs_Excel_Import)]
public async Task<JsonResult> ImportFromExcel()
{
try
{
var jobArgs = await DoImportFromExcelJobArgs(AbpSession.ToUserIdentifier());
var queueState = new EnqueuedState(GetJobQueueName());
IBackgroundJobClient hangFireClient = new BackgroundJobClient();
hangFireClient.Create<ImportTxxxsToExcelJob>(x => x.ExecuteAsync(jobArgs), queueState);
return Json(new AjaxResponse(new { }));
}
catch (Exception ex)
{
return Json(new AjaxResponse(new ErrorInfo(ex.Message)));
}
}
private static string GetOssObjName(int? tenantId, Guid id, bool isThumbnail)
{
string tid = (tenantId ?? 0).ToString();
string ext = isThumbnail ? "thu" : "ori"; //thu - 縮圖、ori - 原圖/原檔案
string hashStr = BitConverter.ToString(MD5.HashData(Encoding.UTF8.GetBytes(tid)), 0).Replace("-", string.Empty).ToLower();
return $"{hashStr[..4]}/{tid}/{id}.{ext}";
}
public async Task SaveAsync(BinaryObject file)
{
if (file?.Bytes == null) { return; }
//1、OSS上傳,成功後直接返回
if (OssPutObject(file.TenantId, file.Id, file.Bytes, isThumbnail: false)) { return; }
//2、若OSS未啟用或者上傳失敗,則直接上傳到資料庫中
await _binaryObjectRepository.InsertAsync(file);
}
private SCMWebhookCacheItem SetAndGetCache(int? tenantId, string keyName = "SubscriptionCount")
{
int tid = tenantId ?? 0; var cacheKey = $"{keyName}-{tid}";
return _cacheManager.GetSCMWebhookCache().Get(cacheKey, () =>
{
int count = 0;
var names = new Dictionary<string, List<WebhookSubscription>>();
UnitOfWorkManager.WithUnitOfWork(() =>
{
using (UnitOfWorkManager.Current.SetTenantId(tenantId))
{
if (_featureChecker.IsEnabled(tid, "SCM.H")) //Feature 核查
{
var items = _webhookSubscriptionRepository.GetAllList(e => e.TenantId == tenantId && e.IsActive == true);
count = items.Count;
foreach (var item in items)
{
if (string.IsNullOrWhiteSpace(item.Webhooks)) { continue; }
var whNames = JsonHelper.DeserializeObject<string[]>(item.Webhooks); if (whNames == null) { continue; }
foreach (string whName in whNames)
{
if (names.ContainsKey(whName))
{
names[whName].Add(item.ToWebhookSubscription());
}
else
{
names.Add(whName, new List<WebhookSubscription> { item.ToWebhookSubscription() });
}
}
}
}
}
});
return new SCMWebhookCacheItem(count, names);
});
}
public override void PostInitialize()
{
...
string defaultEndsWith = _appConfiguration["Job:DefaultEndsWith"];
if (string.IsNullOrWhiteSpace(defaultEndsWith)) { defaultEndsWith = "01"; }
if (AppVersionHelper.MachineName.EndsWith(defaultEndsWith))
{
var workManager = IocManager.Resolve<IBackgroundWorkerManager>();
workManager.Add(IocManager.Resolve<SubscriptionExpirationCheckWorker>());
workManager.Add(IocManager.Resolve<SubscriptionExpireEmailNotifierWorker>());
workManager.Add(IocManager.Resolve<SubscriptionPaymentsCheckWorker>());
workManager.Add(IocManager.Resolve<ExpiredAuditLogDeleterWorker>());
workManager.Add(IocManager.Resolve<PasswordExpirationBackgroundWorker>());
}
...
}
public class RateLimitConfigurationExtensions : RateLimitConfiguration
{
...
public override void RegisterResolvers()
{
ClientResolvers.Add(new ClientIpHeaderResolveContributor(SCMConsts.TenantIdCookieName));
}
}
public class ClientIpHeaderResolveContributor : IClientResolveContributor
{
private readonly string _headerName;
public ClientIpHeaderResolveContributor(string headerName)
{
_headerName = headerName;
}
public Task<string> ResolveClientAsync(HttpContext httpContext)
{
IPAddress clientIp = null;
var headers = httpContext?.Request?.Headers;
if (headers != null && headers.Count > 0)
{
if (headers.ContainsKey(_headerName)) //0 scm_tid
{
string clientId = headers[_headerName].ToString();
if (!string.IsNullOrWhiteSpace(clientId))
{
return Task.FromResult(clientId);
}
}
try
{
if (headers.ContainsKey("X-Real-IP")) //1 X-Real-IP
{
clientIp = IpAddressUtil.ParseIp(headers["X-Real-IP"].ToString());
}
if (clientIp == null && headers.ContainsKey("X-Forwarded-For")) //2 X-Forwarded-For
{
clientIp = IpAddressUtil.ParseIp(headers["X-Forwarded-For"].ToString());
}
}
catch {}
clientIp ??= httpContext?.Connection?.RemoteIpAddress; //3 RemoteIpAddress
}
return Task.FromResult(clientIp?.ToString());
}
}
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './txxxs.component.html',
standalone: true,
imports: [...]
})
export class TxxxsComponent extends AppComponentBase {
...
constructor(
injector: Injector,
changeDetector: ChangeDetectorRef,
) {
super(injector);
setInterval(() => { changeDetector.markForCheck(); }, AppConsts.ChangeDetectorMS);
}
...
}
import { Route } from '@angular/router';
export default [
{ path: 'p120303/t12030301s', loadComponent: () => import('./t12030301s.component').then(c => c.T12030301sComponent), ... },
{ path: 'p120405/t12040501s', loadComponent: () => import('./t12040501s.component').then(c => c.T12040501sComponent), ... },
{ path: 'p120405/t12040502s', loadComponent: () => import('./t12040502s.component').then(c => c.T12040502sComponent), ... },
] as Route[];
function registerLocales(
resolve: (value?: boolean | Promise<boolean>) => void,
reject: any,
spinnerService: NgxSpinnerService
) {
if (shouldLoadLocale()) {
let angularLocale = convertAbpLocaleToAngularLocale(abp.localization.currentLanguage.name);
import(
/* webpackInclude: /(en|en-GB|zh|zh-Hans|zh-Hant)\.mjs$/ */
/* webpackChunkName: "angular-common-locales" */
`/node_modules/@angular/common/locales/${angularLocale}.mjs`).then((module) => {
registerLocaleData(module.default);
resolve(true);
spinnerService.hide();
}, reject);
} else {
resolve(true);
spinnerService.hide();
}
}