public ConcurrentBag<V2SalesOrderGetDataList> ConcurencyGetApp91OrderDetails(List<string> TMCodes, int shopId, ref ConcurrentBag<string> orderErrMsgs)
{
#region 平行查詢
ConcurrentBag<V2SalesOrderGetDataList> result = new ConcurrentBag<V2SalesOrderGetDataList>();
ConcurrentBag<string> errs = new ConcurrentBag<string>();
ConcurrentQueue<string> TMCodeQueues = new ConcurrentQueue<string>();
TMCodes.ForEach(x => TMCodeQueues.Enqueue(x));
Action searchOrderDetail = () =>
{
if (!TMCodeQueues.IsEmpty)
{
string TMCode = string.Empty;
while (TMCodeQueues.TryDequeue(out TMCode))
{
V2SalesOrderGetReqModel reqModel = new V2SalesOrderGetReqModel()
{
ShopId = shopId,
TGCode = null,
TMCode = TMCode,
TSCode = null,
};
try
{
V2SalesOrderGet91API req = new V2SalesOrderGet91API();
var resp = req.Execute(reqModel, shopId);
if (resp.Status == "Success")
{
foreach (var l in resp.Data.List)
{
result.Add(l);
}
}
else
{
//主單編號 , 錯誤原因
errs.Add(TMCode + " , " + resp.ErrorMessage);
}
}
catch (Exception ex)
{
errs.Add(TMCode + " , " + ex.Message);
}
}
}
};
//指派Thread
Parallel.Invoke(searchOrderDetail, searchOrderDetail);
#endregion
//查詢失敗
orderErrMsgs = errs;
return result;
}
/// <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 };
}
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;
}
}
}
var combineBody = Expression.AndAlso(e1.Body, Expression.Invoke(e2, e1.Parameters[0]));
var finalExpression = Expression.Lambda<Func<TestClass, bool>>(combineBody, e1.Parameters).Compile();
public static class ExpressionExtension
{
public static Expression<Func<T, bool>> AndAlso<T>(this Expression<Func<T, bool>> e1, Expression<Func<T, bool>> e2)
{
var combineE = Expression.AndAlso(e1.Body, Expression.Invoke(e2, e1.Parameters[0]));
return Expression.Lambda<Func<T, bool>>(combineE, e1.Parameters);
}
public static Expression<Func<T, bool>> OrElse<T>(this Expression<Func<T, bool>> e1, Expression<Func<T, bool>> e2)
{
var combineE = Expression.OrElse(e1.Body, Expression.Invoke(e2, e1.Parameters[0]));
return Expression.Lambda<Func<T, bool>>(combineE, e1.Parameters);
}
}
Expression<Func<Market, bool>> e1 = e => e.Is_Deleted == isDelete;
Expression<Func<Market, bool>> e2 = e => string.IsNullOrEmpty(marketNo) || e.MarketNo.ToUpper().Contains(marketNo.ToUpper());
return new
{
andMarkets = Ds.PageContext.ShopBandContext.Markets.Where(e1.AndAlso(e2)).ToList(),
orMarkets = Ds.PageContext.ShopBandContext.Markets.Where(e1.OrElse(e2)).ToList(),
};
public static Expression<Func<T, bool>> OrElseAll<T>(this IEnumerable<Expression<Func<T, bool>>> exps)
{
if (exps.Count() == 1)
{
return exps.First();
}
var e0 = exps.First();
var orExp = exps.Skip(1).Aggregate(e0.Body, (x, y) => Expression.OrElse(x, Expression.Invoke(y, e0.Parameters[0])));
return Expression.Lambda<Func<T, bool>>(orExp, e0.Parameters);
}
public static Expression<Func<T, bool>> AndAlsoAll<T>(this IEnumerable<Expression<Func<T, bool>>> exps)
{
if (exps.Count() == 1)
{
return exps.First();
}
var e0 = exps.First();
var orExp = exps.Skip(1).Aggregate(e0.Body, (x, y) => Expression.AndAlso(x, Expression.Invoke(y, e0.Parameters[0])));
return Expression.Lambda<Func<T, bool>>(orExp, e0.Parameters);
}
Expression<Func<Market, bool>> q = e =>
e.Is_Deleted == "N"
&& (string.IsNullOrEmpty(marketNo) || e.MarketNo.ToLower().Contains(marketNo.ToLower()))
&& (string.IsNullOrEmpty(isCombination) || isCombination != "Y" || e.TypeEnum == 200);
if (!string.IsNullOrEmpty(name))
{
var nameList = name.Split(',').Select(e => e.Trim())
.Where(e => !string.IsNullOrEmpty(e));
if (nameList.Any())
{
q = q.AndAlso(nameList
.Select(s => (Expression<Func<Market, bool>>)(e => e.Name.ToLower().Contains(s.ToLower())))
.OrElseAll());
}
}
internal class MergeTool : ExpressionVisitor
{
private readonly ParameterExpression _parameter;
protected override Expression VisitParameter(ParameterExpression node)
{
return base.VisitParameter(_parameter);
}
internal MergeTool(ParameterExpression parameter)
{
_parameter = parameter;
}
public static Expression<Func<T, bool>> MergedExpression<T>(Expression<Func<T, bool>> e1, Expression<Func<T, bool>> e2)
{
ParameterExpression param = Expression.Parameter(typeof(T));
BinaryExpression MergeBody = Expression.AndAlso(e1.Body, e2.Body);
var ReplacedBody = (BinaryExpression)new MergeTool(param).Visit(MergeBody);
return Expression.Lambda<Func<T, bool>>(ReplacedBody, param);
}
}
使用時要 Compile
var mergedExpression = MergeTool.MergedExpression(e1, e2);
var list = testList.Where(mergedExpression.Compile());
using System.Net;
using System.IO;
public partial class TEST : System.Web.UI.Page
{
DB.OrderMain oOrderObj = null;
protected void Page_Load(object sender, EventArgs e)
{
//Setting request header
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("__APIRootURL__");
httpWebRequest.ContentType = "application/json; charset=UTF-8";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("X-LINE-ChannelId", DB.SysConfig.LINEPay.ChannelId);
httpWebRequest.Headers.Add("X-LINE-ChannelSecret", DB.SysConfig.LINEPay.SecretKey);
//加入參數
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string requestJSON = "{\"productName\": \"" + DB.SysConfig.SYSTEM_NAME + "\"," +
"\"productImageUrl\": \"" + DB.SysConfig.URL_Shopping + "images/Logo.jpg\"," +
"\"amount\": " + oOrderObj.TotalAmount() + "," +
"\"currency\": \"TWD\"," +
"\"orderId\": \"" + oOrderObj.DisplayOrderId + "\"," +
"\"confirmUrl\": \"" + DB.SysConfig.URL_Shopping + "Handler/LinePay/GotoComfirm.aspx?Id=" + oOrderObj.Id + "\"," +
"\"cancelUrl\": \"" + DB.SysConfig.URL_Shopping + "Shopping/OrderComplete.aspx?Id=" + oOrderObj.Id + "\"," +
"\"capture\": \"true\"," +
"\"confirmUrlType\": \"CLIENT\"}";
streamWriter.Write(requestJSON);
streamWriter.Flush();
streamWriter.Close();
}
//取得回覆資訊
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
//解讀回覆資訊
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseJSON = streamReader.ReadToEnd();
//將 JSON 轉為物件
GN.LinePay.reserveRes.ReturnJSON oReturnObj = (GN.LinePay.reserveRes.ReturnJSON)Newtonsoft.Json.JsonConvert.DeserializeObject(responseJSON, typeof(GN.LinePay.reserveRes.ReturnJSON));
if (oReturnObj.returnCode == "0000")
{
//成功
}
else
{
//失敗
string ErrMsg = "Error Code: " + oReturnObj.returnCode + "\r\n" + oReturnObj.returnMessage;
}
}
}
}
Imports System.Net
Imports System.IO
Partial Class TEST
Inherits System.Web.UI.Page
Dim oOrderObj As DB.OrderMain
Private Sub Admin_TEST_Load(sender As Object, e As EventArgs) Handles Me.Load
'Setting request header
Dim httpWebRequest As HttpWebRequest = WebRequest.Create("__APIRootURL__")
httpWebRequest.ContentType = "application/json; charset=UTF-8"
httpWebRequest.Method = "POST"
httpWebRequest.Headers.Add("X-LINE-ChannelId", DB.SysConfig.LINEPay.ChannelId)
httpWebRequest.Headers.Add("X-LINE-ChannelSecret", DB.SysConfig.LINEPay.SecretKey)
'加入參數
Using streamWriter As New StreamWriter(httpWebRequest.GetRequestStream())
Dim requestJSON As String = "{""productName"": """ + DB.SysConfig.SYSTEM_NAME + """," +
"""productImageUrl"": """ + DB.SysConfig.URL_Shopping + "images/Logo.jpg""," +
"""amount"": " + oOrderObj.TotalAmount() + "," +
"""currency"": ""TWD""," +
"""orderId"": """ + oOrderObj.DisplayOrderId + """," +
"""confirmUrl"": """ + DB.SysConfig.URL_Shopping + "Handler/LinePay/GotoComfirm.aspx?Id=" + oOrderObj.Id + """," +
"""cancelUrl"": """ + DB.SysConfig.URL_Shopping + "Shopping/OrderComplete.aspx?Id=" + oOrderObj.Id + """," +
"""capture"": ""true""," +
"""confirmUrlType"": ""CLIENT""}"
streamWriter.Write(requestJSON)
streamWriter.Flush()
streamWriter.Close()
End Using
'取得回覆資訊
Dim httpResponse As HttpWebResponse = httpWebRequest.GetResponse
'解讀回覆資訊
Using streamReader As New StreamReader(httpResponse.GetResponseStream())
Dim responseJSON As String = streamReader.ReadToEnd()
'將 JSON 轉為物件
Dim oReturnObj As GN.LinePay.reserveRes.ReturnJSON = Newtonsoft.Json.JsonConvert.DeserializeObject(responseJSON, GetType(GN.LinePay.reserveRes.ReturnJSON))
Dim ResMsg As String = ""
If oReturnObj.returnCode = "0000" Then
'成功
Else
'失敗
End If
End Using
End Sub
End Class
<a class="del" href="#" data-yano="1250453286" data-pdno="04360003">
<img src="/TC/template/Shopping/images/del.png" alt="">
</a>
<Item time="2016-01-11T05:39:01" page="/fr/iconic-bright-cushion-spf-50-pa-nude-perfection-compact-foundation/p/5490/c/30"
url="http://www.shopunt.com/fr/iconic-bright-cushion-spf-50-pa-nude-perfection-compact-foundation/p/5490/c/30?utm_source=edm&utm_medium=email&utm_content=20160107_cushion_4&utm_campaign=makeup&OutAD_Id=5825" username="Not Member" browserName="Chrome" browserVersion="34.0" userAgent="Mozilla/5.0 (Linux; Android 5.1.1; SAMSUNG SM-N915FY Build/LMY47X) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/2.1 Chrome/34.0.1847.76 Mobile Safari/537.36" RemoteIP="37.160.206.7" Ref="No Ref" RequestType="GET" Ver="3">
<ErrMsg>
</ErrMsg>
<ErrStack> 於 System.Web.CachedPathData.ValidatePath(String physicalPath)
於 System.Web.HttpApplication.PipelineStepManager.ValidateHelper(HttpContext context)</ErrStack>
<Post>
</Post>
<Cookie>
</Cookie>
</Item>