UWInfo Blog
發表新文章
[Join] | [忘記密碼] | [Login]
搜尋

搜尋意見
文章分類-#Author#
[所有文章分類]
所有文章分類
  • ASP.NET (48)
  • ASP.NET2.0 (15)
  • ASP.NET4.0 (34)
  • JavaScript (49)
  • jQuery (26)
  • FireFox (4)
  • UW系統設定 (3)
  • SQL (39)
  • SQL 2008 (25)
  • mirror (4)
  • SVN (4)
  • IE (9)
  • IIS (20)
  • IIS6 (1)
  • 閒聊 (7)
  • W3C (6)
  • 作業系統 (9)
  • C# (24)
  • CSS (12)
  • FileServer (1)
  • HTML 5 (11)
  • CKEditor (3)
  • UW.dll (13)
  • Visual Studio (16)
  • Browser (8)
  • SEO (1)
  • Google Apps (3)
  • 網站輔助系統 (4)
  • DNS (5)
  • SMTP (4)
  • 網管 (11)
  • 社群API (3)
  • SSL (4)
  • App_Inventor (1)
  • URLRewrite (2)
  • 開發工具 (6)
  • JSON (1)
  • Excel2007 (1)
  • 試題 (3)
  • LINQ (1)
  • bootstrap (0)
  • Vue (3)
  • IIS7 (3)
  • foodpanda (2)
  • 編碼 (2)
  • 資安 (3)
  • Sourcetree (1)
  • MAUI (1)
  • CMD (1)
  • my sql (1)
最新回應
  • Newtonsoft.Json.JsonConvert.DeserializeObject 失敗的情況
    test...more
  • dotnet ef dbcontext scaffold
    ...more
  • [ASP.NET] 利用 aspnet_regiis 加密 web.config
    ...more
  • IIS ARR (reverse proxy) 服務安裝
    ...more
  • [錯誤訊息] 請加入 ScriptResourceMapping 命名的 jquery (區分大小寫)
    ...more
  • 用 Javascript 跨網頁讀取 cookie (Cookie cross page, path of cookie)
    ...more
  • 線上客服 - MSN
    本人信箱被盜用以致資料外洩,是否可以請貴平台予以協助刪除該信箱之使用謝謝囉...more
  • 插入文字到游標或選取處
    aaaaa...more
  • IIS 配合 AD (Active Directory) 認証, 使用 .Net 6.0
    太感謝你了~~~你救了我被windows 認證卡了好幾天QQ...more
  • PostgreSQL 的 monitor trigger
    FOR EACH ROW 可能要改為 FOR EACH STATEMENT ...more
標籤
  • sa
  • C#[t]
  • vb ORDER B
  • 備註
  • iisre
  • remote
  • drop
  • HTML
  • images
  • 8
  • C
  • vb.net
  • 1406
  • pear
  • ti
  • backup
  • There is
  • 0
  • 3013
  • MaxWorkIte
  • 網址
  • ad
  • ef
  • Button
  • dotnet
  • entity
  • ie8
  • 備份
  • -2154 UNIO
  • postgre
  • SEO
  • postgresql
  • if
  • 日期
  • -5672
  • 4hew.com
  • 圖片
  • IE
  • VS
  • 耗時
  • sourcetree
  • 7527
  • Needs Lock
  • 15
  • asp
  • CKEditor
  • 0.6aVNC
  • cache
  • 230
  • ssl
頁數 1 / 2 下一頁
搜尋 datetime 結果:
PrintDocument 另存成 PDF
如果列印主機是 windows server 主機,通常會有 "Microsoft Print to PDF" 名稱的印表機
那使用 Print Document 物件另存成 PDF code 如下
pd.PrinterSettings.PrinterName = "Microsoft Print to PDF";
pd.PrinterSettings.PrintToFile = true;
pd.PrinterSettings.PrintFileName = @"C:\TEMP\XPS\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf";
More...
darren, 2025/5/12 下午 04:36:12
mysql 使用 EF model 要注意的地方
近日處理我們公司某個使用 my sql 的專案,已經被雷的幾次,紀錄一下

1.  使用 EF Scaffolding 指令去更新 Model ,有些欄位原本是明確型別 變成 可null型別
     也就是本來是 datetime 變成 datetime?, int 變成 int?
     看起來是一些 view 的欄位會有這些狀況,這時就要去 git revert ,避免build專案又一堆錯誤
2.  使用 IQueryable 語法處理時間要小心,不要在裡面計算時間。
     
DateTime shouldBeGiveCoinDateTime = DateTime.Now.AddDays(-14);
return dbContext.ViewOrderForCoinCronJob.AsNoTracking().Where(x =>
    x.CompletedAt <= shouldBeGiveCoinDateTime
    && x.CreatedAt >= DateTime.Now.AddYears(-1) // -> 這裡轉換mysql指令會出錯
    && x.DeletedAt == null
    && x.CoinAmount > 0
    && x.Status == (byte)ORDER_STATUS.COMPLETED
    && dbContext.PackingMain.Any(y => y.OrderId == x.Id)
    && x.IsGiveCoin != 0
    && !dbContext.CoinLog.Any(y =>
        y.OrderId == x.Id
        && y.StrKey.Contains(COIN_LOG.STRING_KEY_PREFIX.ORDER_ACCUMULATION)
    )
).ToList();

要把時間計算先算出來,再帶入式子
DateTime shouldBeGiveCoinDateTime = DateTime.Now.AddDays(-14);
DateTime createDateStartAt = DateTime.Now.AddYears(-1); // -> 先算出日期
return dbContext.ViewOrderForCoinCronJob.AsNoTracking().Where(x =>
    x.CompletedAt <= shouldBeGiveCoinDateTime
    && x.CreatedAt >= createDateStartAt // -> 帶入算好的日期
    && x.DeletedAt == null
    && x.CoinAmount > 0
    && x.Status == (byte)ORDER_STATUS.COMPLETED
    && dbContext.PackingMain.Any(y => y.OrderId == x.Id)
    && x.IsGiveCoin != 0
    && !dbContext.CoinLog.Any(y =>
        y.OrderId == x.Id
        && y.StrKey.Contains(COIN_LOG.STRING_KEY_PREFIX.ORDER_ACCUMULATION)
    )
).ToList();


 
More...
darren, 2025/3/10 下午 05:43:38
關於 Entity Framework Extensions 的 UpdateFromQueryAsync
這個指令還是會把所有的資料 Select 出來,再更新

原指令:

UPDATE Job Set En_Status = 200 Where En_Status = 100 and LastTouchAt < '2023-05-06 12:34:56'
其中  '2023-05-06 12:34:56' 是 DateTime.Now.AddMinutes(-2) 的結果(Web Server 端的時間扣 2 分鐘)

但,若是改使用 UpdateFromQueryAsync 如下:
var c = await Ds.NewContext.GvContext.Jobs.Where(j => j.En_Status == Cst.Job.Status.Running && j.LastTouchAt < DateTime.Now.AddMinutes(-2))
                .UpdateFromQueryAsync(j => new Ds.Gv.Job { En_Status = Cst.Job.Status.ReStarting });

產生的 SQL 如下:
UPDATE A 
SET A.[En_Status] = @zzz_BatchUpdate_0
FROM [Job] AS A
INNER JOIN ( SELECT [j].[Id], [j].[CancelledAt], [j].[CancelledBy], [j].[En_Status], [j].[EndAt], [j].[Exception], [j].[Filename], [j].[InformationJson], [j].[InitAt], [j].[Is_CheckOnly], [j].[LastTouchAt], [j].[LastTouchMessage], [j].[LoopStartAt], [j].[Name], [j].[ScheduleId], [j].[TotalTouch], [j].[TouchCount]
FROM [Job] AS [j]
WHERE [j].[En_Status] = 100 AND [j].[LastTouchAt] < DATEADD(minute, CAST(-2.0E0 AS int), GETDATE())
           ) AS B ON A.[Id] = B.[Id]

有兩個要注意的地方:
1. 它會先 Select 全欄位,再做更新

2. 它的時間是 DB Server 的現在時間。不是 Web Server 端的時間。


順便記錄一下。若是要執行 Update xx Ser cc = cc + 1 Where ...

EF 可寫為:
var c = await Ds.NewContext.GvContext.Jobs.Where(j => j.En_Status == Cst.Job.Status.Running && j.LastTouchAt < DateTime.Now.AddMinutes(-2))
                .UpdateFromQueryAsync(j => new Ds.Gv.Job { TotalTouch = j.TotalTouch + 1 });

轉換的 SQL 為:
UPDATE A 
SET A.[TotalTouch] = B.[TotalTouch] + 1
FROM [Job] AS A
INNER JOIN ( SELECT [j].[Id], [j].[CancelledAt], [j].[CancelledBy], [j].[En_Status], [j].[EndAt], [j].[Exception], [j].[Filename], [j].[InformationJson], [j].[InitAt], [j].[Is_CheckOnly], [j].[LastTouchAt], [j].[LastTouchMessage], [j].[LoopStartAt], [j].[Name], [j].[ScheduleId], [j].[TotalTouch], [j].[TouchCount]
FROM [Job] AS [j]
WHERE [j].[En_Status] = 100 AND [j].[LastTouchAt] < DATEADD(minute, CAST(-2.0E0 AS int), GETDATE())
           ) AS B ON A.[Id] = B.[Id]
More...
Bike, 2023/4/29 下午 08:44:31
.Net 6 的 Captcha 實做
產生 FileStreamResult 物件的 function 如下: (目前置於 SU 之中,以便轉移)

        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" };
        }



輸出用的 Controller 和 Action 如下:

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);
        }
    }
}
More...
Bike, 2022/9/25 下午 10:03:44
資安問題 -- Random 的替代 function
        static System.Security.Cryptography.RandomNumberGenerator RandomNumberGenerator = null;

        /// <summary>
        /// 回傳大於等於 0 小於 1
        /// </summary>
        /// <returns></returns>
        public static double NextDouble()
        {
            if (RandomNumberGenerator == null || LastRandomGenerateTime < DateTime.Now.AddMinutes(-1))
            {
                RandomNumberGenerator = System.Security.Cryptography.RandomNumberGenerator.Create();
            }

            // Generate four random bytes
            byte[] four_bytes = new byte[4];
            RandomNumberGenerator.GetBytes(four_bytes);

            // Convert the bytes to a UInt32
            uint scale = BitConverter.ToUInt32(four_bytes, 0);

            // And use that to pick a random number >= min and < max
            // 0 <= (scale / (uint.MaxValue + 1.0)) < 1
            return scale / (uint.MaxValue + 1.0);
        }

        /// <summary>
        /// 回傳值介於 min ~ (max - 1)
        /// </summary>
        /// <param name="min"></param>
        /// <param name="max"></param>
        /// <returns></returns>
        public static int GetRandomInt(int min, int max)
        {
            if(max < min)
            {
                throw new Exception("最大值不可小於最小值");
            }

            // Generate four random bytes
            byte[] four_bytes = new byte[4];
            RandomNumberGenerator.GetBytes(four_bytes);

            // And use that to pick a random number >= min and < max
            return (int)(min + (max - min) * NextDouble()); //因為 NextDouble 會小於 1,所以用無條件捨去.
        }

        /// <summary>
        /// 產生 0 ~ (max - 1) 的亂數
        /// </summary>
        /// <param name="max"></param>
        /// <returns></returns>
        public static int GetRandomInt(int max)
        {
            return GetRandomInt(0, max);
        }

        /// <summary>
        /// 產生 0 ~ (int.MaxValue - 1) 的亂數
        /// </summary>
        /// <returns></returns>
        public static int GetRandomInt()
        {
            return GetRandomInt(int.MaxValue);
        }
More...
Bike, 2022/9/22 下午 08:30:03
The JSON value could not be converted to System.Nullable`1[System.DateTime]
.net 6 在 model 中上傳日期字串時,如果遇到 "The JSON value could not be converted to System.Nullable`1[System.DateTime]"  這個錯誤,解決方法如下:

1. 安裝套件: Microsoft.AspNetCore.Mvc.NewtonsoftJson

2. 在 program.cs 中,原來來的

builder.Services.AddControllers()

改為 (其 options 的部份非必要)

builder.Services.AddControllers()
    .AddNewtonsoftJson(options =>
     {
         options.SerializerSettings.ContractResolver = new Su.CamelCaseContractResolver();
     });
More...
Bike, 2022/8/21 下午 10:12:43
PostgreSQL 的 monitor trigger
--建立 table (要記得改 XXX)
CREATE TABLE IF NOT EXISTS public.table_monitor
(
    table_name text COLLATE pg_catalog."default" NOT NULL,
    update_at timestamp without time zone NOT NULL DEFAULT now(),
    update_count bigint NOT NULL DEFAULT 0,
    CONSTRAINT table_monitor_pkey PRIMARY KEY (table_name)
)

TABLESPACE pg_default;

ALTER TABLE IF EXISTS public.table_monitor
    OWNER to XXX;

-- 這一段只要執行一次
CREATE OR REPLACE FUNCTION public.table_monitor_trigger_fnc()
    RETURNS trigger
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE NOT LEAKPROOF
AS $BODY$
BEGIN
     Update public.table_monitor Set update_count = update_count + 1, update_at = now()  Where table_name = TG_TABLE_NAME; 
RETURN NEW;
END;
$BODY$;

ALTER FUNCTION public.table_monitor_trigger_fnc()
    OWNER TO XXX;

-- 對於被監控的 table, 要執行以下的指令,記得 monitor_table_name 要改為 table 的名字(要符合大小寫)
INSERT INTO public.table_monitor (table_name, update_at, update_count) VALUES ('monitor_table_name', '2000-01-01', 0) ON CONFLICT DO NOTHING;

CREATE OR REPLACE TRIGGER table_monitor_trigger
    AFTER INSERT OR DELETE OR UPDATE 
    ON monitor_table_name
    FOR EACH STATEMENT
    EXECUTE FUNCTION public.table_monitor_trigger_fnc();

監控用的程式碼:
public static void UpdateTableCache()
{
    //標記自已是正在執行的 Thread. 讓舊的 Thread 在執行完畢之後, 應該會自動結束. 以防舊的 Thread 執行超過 10 秒.
    CurrentThreadId = System.Threading.Thread.CurrentThread.ManagedThreadId;

    try
    {
        //確認自已是正在執行的 Thread, 重覆執行. (另一個 Thread 插入執行)
        while (CurrentThreadId == System.Threading.Thread.CurrentThread.ManagedThreadId)
        {
            LastUpdateDate = DateTime.Now;

            foreach (var dbId in CachedDbs)
            {
                var sql = @"select * from table_monitor";

                var dt = Su.PgSql.DtFromSql(sql, dbId);

                foreach (DataRow row in dt.Rows)
                {
                    string changeId = row["update_count"].DBNullToDefault();
                    string CacheKey = TableCacheKey(dbId, row["table_name"].DBNullToDefault());
                    ObjectCache cache = MemoryCache.Default;

                    string OldValue = (string)cache[CacheKey];

                    if (OldValue == null)
                    {
                        cache.Set(CacheKey, changeId, DateTime.MaxValue);
                    }
                    else
                    {
                        if (changeId != OldValue)
                        {
                            cache.Remove(CacheKey);
                            cache.Set(CacheKey, changeId, DateTime.MaxValue);
                        }
                    }
                }
            }

            //每兩秒檢查一次
            System.Threading.Thread.Sleep(2000);
        }
    }
    catch (Exception)
    {
        //依經驗, 只要 DB 能通, 這裡幾乎不會有問題, 所以這裡暫時不處理, 未來有問題時可以考慮寫入文字檔比較好.
    }
}
More...
Bike, 2022/7/20 上午 10:05:39
DtToWorkSheet 的預設日期格式
1. 增加 dateTimeFormat, isAutoToDate
2. 增加 static string ExportDateTimeFormat
More...
Bike, 2022/1/6 上午 11:21:07
SU 的新規格 RFP
1. .Net Core 5.0 使用.
2. 可切換後, 適用於 MsSQL, MySql, Oracle
3. 預設所有 SQL 執行時要經過 SQL Injection 檢查.
(移除 "CheckDangerSQL", 併入 IsSqlInjection) 

預設會把 CR 和 LF 換成 空白,以免 sql injection 檢查發生錯誤, 有參數可以控制這個行為。sql 和 資料應該要分開,sql 中的 CR 和 LF 被換成空白應該不會有問題。

4. 不要再使用 SqlStr, 改用 SqlValue (避免誤用, SqlStr 有一個問題, 若是忘了加上 '' 會有可能造成 sql injection)

5. ORM 的 Class Name, 若遇到全大寫的字節, 要先轉小寫, 再把第一個字母變大寫.

6. CopyPropertiesTo, CopyTo.. 
   SetValue 時, 若發生錯誤, 要顯示錯誤欄位名稱. (Tmi 的版本, ObjUtil.cs)

7. CopyFromDataRow: 
   string 自動轉 DateTime
   string 自動轉  int, long, decimal..

8. Criteria 的 In 和 operator (|) 要接 list 做為參數, 不要再直接用字串做參數.

9. OrderBy 增加 by column 且可以多個串接

10. Update 時可以用 sql 語法 (參考聖宜的  GetSetFieldWithExpression)

11. 檢查 SQL Injection 的方法改為先把 \r 和 \n 用空白取代,再檢查, 再取代參數。

12. DtFromSql 和 ExecuteSql 傳入 connection 和 transaction 的版本先刪除,未來有需要再增加。 
More...
Bike, 2021/10/18 下午 04:29:15
DateTime porperty 的 Model Validation
對 DateTime 的 property 直接設定 Require 的 Validation 會失敗. 因為茌是 client 送來空白, 會發生轉型的錯誤, 而不是 Require 的錯誤

可以把該 property 改設定為 DateTime? 來解決這個問題.
More...
Bike, 2021/9/23 下午 10:26:41
|< 12 >|
頁數 1 / 2 下一頁
~ Uwinfo ~