using Ds;
using Ds.Gv;
using iText.Kernel.Geom;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NPOI.SS.Formula.Functions;
using NPOI.SS.Util;
using Su;
using System.Linq.Expressions;
namespace CallCampaign.Api
{
/// <summary>
/// 行銷活動
/// </summary>
[Route("api/call-campaign")]
[ApiController]
[SetAuthorizationFilter(Sh.AuthCode.不設限)]
public class ReserveCampaignController : Controller
{
/// <summary>
/// 取得行銷活動列表
/// </summary>
/// <param name="reserveCampaignName"></param>
/// <param name="currentPage"></param>
/// <param name="pageSize"></param>
/// <param name="orderByName"></param>
/// <param name="sort"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
[HttpGet("")]
public async Task<object> ListAsync([FromQuery] string reserveCampaignName = "", [FromQuery] int? currentPage = 1, [FromQuery] int? pageSize = 20, [FromQuery] string orderByName = "OrderNo", [FromQuery] string sort = "asc")
{
if (pageSize > 500)
{
pageSize = 500;
}
if (!(sort == "asc" || sort == "desc"))
{
throw new CustomException(System.Net.HttpStatusCode.BadRequest, "sort只能是asc或desc");
}
var temp = new V_ReserveCampaign().GetType().GetProperty(orderByName);
if (temp == null)
{
throw new CustomException(System.Net.HttpStatusCode.BadRequest, "不存在欄位");
}
Expression<Func<V_ReserveCampaign, bool>> q = p => p.Is_Deleted == "N"
&& (string.IsNullOrEmpty(reserveCampaignName) || (p.ReserveCampaignName != null && p.ReserveCampaignName.Contains(reserveCampaignName)))
;
if (orderByName.ToLower().Trim() != "id")
{
orderByName += " " + sort + ", id desc";
}
else
{
orderByName += " " + sort;
}
var ct = NewContext.GvContext;
var list = await ct.GetPageListAsync(q, columns: "Id, ReserveCampaignName, OrderNo, StartAt, EndAt, ModifierName, ModifyDate, CreatorName, CreateDate", page: currentPage ?? 1, pageSize: pageSize ?? 20, orderByName);
//var list = await ct.GetPageListAsync(q, page: currentPage ?? 1, pageSize: pageSize ?? 20, orderByName + " " + sort);
return list;
}
/// <summary>
/// 取得行銷活動
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
[HttpGet("get")]
public async Task<dynamic> GetAsync([FromQuery] int Id)
{
var res = await Ds.NewContext.GvContext.ReserveCampaigns.Where(r => r.Id == Id)
.FirstOrDefaultAsync();
if (res == null)
{
throw new CustomException(System.Net.HttpStatusCode.BadRequest, "查無資料 " + Id.ToString());
}
return res;
}
/// <summary>
/// 建立行銷活動
/// </summary>
/// <param name="dto"></param>
/// <returns></returns>
/// <exception cref="CustomException"></exception>
[HttpPost("")]
public async Task<object> CreateAsync(Dtos.CreateReserveCampaign dto)
{
var ct = NewContext.GvContext;
var res = await Models.ReserveCampaignHelper.CreateReserveCampaignAsync(ct, dto);
return res;
}
/// <summary>
/// 編輯行銷活動
/// </summary>
/// <param name="dto"></param>
/// <returns></returns>
/// <exception cref="CustomException"></exception>
[HttpPatch("")]
public async Task<object> UpdateAsync(Dtos.UpdateReserveCampaign dto)
{
var ct = NewContext.GvContext;
var res = await Models.ReserveCampaignHelper.UpdateReserveCampaignAsync(ct, dto);
return res;
}
/// <summary>
/// 刪除行銷活動
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
/// <exception cref="CustomException"></exception>
[HttpDelete("")]
public async Task<object> DeleteAsync([FromQuery] int id)
{
var res = await Ds.NewContext.GvContext.MarkDeleteAsync<Ds.Gv.ReserveCampaign>(id, Sh.ModifyInfo);
return res;
}
}
}
/// <summary>
/// 取得列表
/// </summary>
/// <param name="name"></param>
/// <param name="currentPage"></param>
/// <param name="pageSize"></param>
/// <param name="orderByName"></param>
/// <param name="sort"></param>
/// <returns></returns>
[HttpGet("")]
public object List([FromQuery] string name = "", [FromQuery] int? currentPage = 1, [FromQuery] int? pageSize = 20, [FromQuery] string orderByName = "OrderNo", [FromQuery] string sort = "asc")
{
return "";
}
/// <summary>
/// 取得明細資料
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
[HttpGet("get")]
public object Get([FromQuery] int id)
{
return "";
}
/// <summary>
/// 建立
/// </summary>
/// <param name="dto"></param>
/// <returns></returns>
/// <exception cref="CustomException"></exception>
[HttpPost("")]
public object Create(Dtos.PhysicalCheckUpType dto)
{
return "";
}
/// <summary>
/// 編輯
/// </summary>
/// <param name="dto"></param>
/// <returns></returns>
/// <exception cref="CustomException"></exception>
[HttpPatch("")]
public object Update(Dtos.PhysicalCheckUpType dto)
{
return "";
}
/// <summary>
/// 刪除
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
/// <exception cref="CustomException"></exception>
[HttpDelete("")]
public object Delete([FromQuery] int id)
{
return 1;
}
PromiseAll: async function (array) {
let taskList = [];
let propList = [];
for (let obj of array) {
for (let prop in obj) {
taskList.push(obj[prop]);
propList.push(prop);
}
}
let resp = await Promise.all(taskList);
let result = {};
let counter = 0;
for (let prop of propList) {
result[prop] = resp[counter];
counter += 1;
}
return result;
}
const taskList = [{
adPosition : BannerPositionDataService.GetList(),
big : BannerDataService.GetList(100),
smallTop : BannerDataService.GetOne(200),
smallBottom : BannerDataService.GetOne(300),
section2 : BannerDataService.GetList(400),
section3 : BannerDataService.GetList(500),
section4 : BannerDataService.GetList(600),
recommends : ProductDataService.GetRndList()
}];
let resps = await UJ.PromiseAll(taskList);
DeepBinding: function (vueData, data) {
if (Array.isArray(data)) {
if (!Array.isArray(vueData)) {
vueData = [];
} else {
vueData.splice(0);
}
for (let prop in data) {
vueData.push(data[prop]);
}
}
else if (typeof (data) === 'object') {
if (Object.keys(data).length === 0) {
return;
}
for (let prop in data) {
if (vueData[prop] === undefined || data[prop] === null ||
(!Array.isArray(vueData[prop] && vueData !== null && typeof (data) !== 'object'))) {
vueData[prop] = data[prop];
} else {
this.DeepBinding(vueData[prop], data[prop]);
}
}
} else {
vueData = data;
}
}
UJ.DeepBinding(this, resp);
/// <summary>
/// 會把物件 Parameter 的各 Property 帶入 SQL 中.
/// </summary>
/// <param name="dbct"></param>
/// <param name="sql"></param>
/// <param name="parameters"></param>
/// <returns></returns>
public static async Task<int> ExecuteParameterSqlAsync(this DbContext dbct, string sql, object parameters)
{
return await dbct.Database.ExecuteSqlRawAsync(sql, parameters.ToSqlParamsArray());
}
public async Task<object> EfTest()
{
var dbct = Ds.NewContext.GvContext;
var insertSql = @"Insert into ProfileEvent(JobId,[Name],GvShoplineId,LiShoplineId,Phone,Email,LineId,GaClientId)
Values(@JobId, @Name, null , null , null , @Email, @GaClientId , @GaClientId )";
//執行 SQL 的原生寫法
await dbct.Database.ExecuteSqlRawAsync(insertSql, new object[]
{
new SqlParameter("@JobId", 10),
new SqlParameter("@Email", "XX'TT"),
new SqlParameter("@Name", "AA'BB"),
new SqlParameter("@GaClientId", "GaClientId"),
});
//執行 SQL 的擴充寫法
await dbct.ExecuteParameterSqlAsync(insertSql, new
{
JobId = 10,
Email = "XX'TT",
Name = "AA'BB",
GaClientId = "GaClientId"
});
//關於查詢
string name = "%'B%";
//原生寫法
var res1 = await dbct.ProfileEvents.FromSqlRaw("Select top 100 * from ProfileEvent where Name like @name",
new object[]
{
new SqlParameter("@name", "%'B%")
})
.ToListAsync();
//擴充, object to SqlParameter array
var res2 = await dbct.ProfileEvents.FromSqlRaw("Select top 100 * from ProfileEvent where Name like @name",
new { name }.ToSqlParamsArray())
.ToListAsync();
var res3 = await dbct.ProfileEvents.FromSql($"Select top 100 * from ProfileEvent where Name like {name}")
.ToListAsync();
var res4 = await dbct.ProfileEvents.FromSqlInterpolated($"Select top 100 * from ProfileEvent where Name like {name}")
.ToListAsync();
return new { res1, res2, res3, res4 };
}
<ItemGroup>
<PackageReference Include="sqlite-net-pcl" Version="1.8.116" />
<PackageReference Include="SQLiteNetExtensions.Async" Version="2.1.0" />
<PackageReference Include="SQLitePCLRaw.bundle_green" Version="2.1.4" />
<PackageReference Include="SQLitePCLRaw.core" Version="2.1.4" />
<PackageReference Include="SQLitePCLRaw.lib.e_sqlite3" Version="2.1.4" />
<PackageReference Include="SQLitePCLRaw.provider.dynamic_cdecl" Version="2.1.4" />
<PackageReference Include="System.Data.DataSetExtensions" Version="4.5.0" />
</ItemGroup>
static List<Brush> CaptchaBrushes = null;
public static FileStreamResult CreateCaptcha(string captcha)
{
if (CaptchaBrushes == null)
{
CaptchaBrushes = new List<Brush>();
CaptchaBrushes.Add(Brushes.White);
CaptchaBrushes.Add(Brushes.Gold);
CaptchaBrushes.Add(Brushes.LightSkyBlue);
CaptchaBrushes.Add(Brushes.LimeGreen);
CaptchaBrushes.Add(Brushes.AliceBlue);
CaptchaBrushes.Add(Brushes.AntiqueWhite);
CaptchaBrushes.Add(Brushes.BurlyWood);
CaptchaBrushes.Add(Brushes.Silver);
}
int width = 90;
int height = 45;
//https://stackoverflow.com/questions/61365732/cannot-access-a-closed-stream-when-returning-filestreamresult-from-c-sharp-netc
//Using statements close and unload the variable from memory set in the using statement which is why you are getting an error trying to access a closed memory stream.You don't need to use a using statement if you are just going to return the result at the end.
//這個 memory stream 不用關閉或 dispose
var ms = new MemoryStream();
// 釋放所有在 GDI+ 所佔用的記憶體空間 ( 非常重要!! )
using (Bitmap _bmp = new Bitmap(width, height))
using (Graphics _graphics = Graphics.FromImage(_bmp))
using (Font _font = new Font("Courier New", 24, FontStyle.Bold)) // _font 設定要出現在圖片上的文字字型、大小與樣式
{
// (封裝 GDI+ 繪圖介面) 所有繪圖作業都需透過 Graphics 物件進行操作
_graphics.Clear(Color.Black);
// 如果想啟用「反鋸齒」功能,可以將以下這行取消註解
//_graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
// 將亂碼字串「繪製」到之前產生的 Graphics 「繪圖板」上
var x = 10;
for(var i = 0; i < captcha.Length; i++)
{
_graphics.DrawString(captcha.Substring(i, 1), _font, CaptchaBrushes[Su.MathUtil.GetRandomInt(CaptchaBrushes.Count)], x, Su.MathUtil.GetRandomInt(15));
x += 10 + Su.MathUtil.GetRandomInt(10);
}
// 畫線
_graphics.DrawLine(new Pen(CaptchaBrushes[Su.MathUtil.GetRandomInt(CaptchaBrushes.Count)], 1),
Su.MathUtil.GetRandomInt(0, Convert.ToInt32((width * 0.9 / 2))), 0, Su.MathUtil.GetRandomInt(Convert.ToInt32(width / 2), Convert.ToInt32(width * 1.9 / 2)), height);
_graphics.DrawLine(new Pen(CaptchaBrushes[Su.MathUtil.GetRandomInt(CaptchaBrushes.Count)], 1),
Su.MathUtil.GetRandomInt(Convert.ToInt32(width / 2), Convert.ToInt32(width * 1.9 / 2)), 0, Su.MathUtil.GetRandomInt(0, Convert.ToInt32((width * 0.9 / 2))), height);
_graphics.DrawLine(new Pen(CaptchaBrushes[Su.MathUtil.GetRandomInt(CaptchaBrushes.Count)], 1),
0,
Su.MathUtil.GetRandomInt(height / 2),
width,
height / 2 + Su.MathUtil.GetRandomInt(height / 2)
);
_graphics.DrawLine(new Pen(CaptchaBrushes[Su.MathUtil.GetRandomInt(CaptchaBrushes.Count)], 1),
0,
height / 2 + Su.MathUtil.GetRandomInt(height / 2),
width,
Su.MathUtil.GetRandomInt(height / 2)
);
_bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
}
ms.Seek(0, SeekOrigin.Begin);
// Controller 的型別為 FileResult
return new FileStreamResult(ms, "image/jpeg")
{ FileDownloadName = $"{DateTime.Now.Ymdhmsf()}.jpg" };
}
namespace Web.Controllers
{
public class CaptchaController : Controller
{
[Route("captcha")]
public async Task<FileStreamResult> Index()
{
//產生 Captcha 並存入 Session 之中。目前是四位數字
string captcha = (await Ah.ReGetAsync<object>("api/kol/create-captcha-code")).ToString();
//產生圖檔並回傳 FileStreamResult
return Su.Wu.CreateCaptcha(captcha);
}
}
}
int tries = 0;
while (tries < Su.PgSql.maxTransactionAborted)
{
try
{
using (var scop = new System.Transactions.TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
var context = ShopBandContext.Context;
updateCount = await context.UpdateAsync<MarketDiscount>(dto, Sc.ModifyInfo,
onlyColumns: "StartAt,EndAt,NewPrice,FrontEndMemo,BackEndMemo");
scop.Complete();
break; //這個 Break 很重要
}
}
catch (Exception ex)
{
// 我發現因為是非同步模式,所以要檢查很多層的 InnerException
if (tries < Su.PgSql.maxTransactionAborted
&& ((ex.InnerException != null && ex.InnerException is Npgsql.PostgresException && ((Npgsql.PostgresException)ex.InnerException).SqlState == "40001")
|| (ex.InnerException.InnerException != null && ex.InnerException.InnerException is Npgsql.PostgresException && ((Npgsql.PostgresException)ex.InnerException.InnerException).SqlState == "40001")))
{
//隨機休息 10 ~ 20 ms, 等另一個 job 完工
System.Threading.Thread.Sleep(Su.MathUtil.Random.Next(10, 20));
tries++;
}
else
{
throw;
}
}
}