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
標籤
  • country
  • ie
  • 2515
  • AD
  • GN
  • cross
  • MSkvKiovQW
  • 16
  • 408
  • print
  • cache
  • request
  • CS
  • Data
  • [u2]
  • bluk
  • 試
  • recovery O
  • max
  • date[t] OR
  • image
  • Table
  • if
  • 220
  • end
  • �
  • list
  • 按鈕
  • 搬家
  • canvas
  • net
  • user
  • en
  • uw
  • 網址
  • dead lock
  • vb.net
  • 鏡像
  • jq
  • 問題
  • ios
  • javascript
  • 20
  • 80
  • sqldepende
  • visual
  • 下載
  • 具有潛在危險
  • 594
  • date
頁數 1 / 2 下一頁
搜尋 debug 結果:
使用 Dependency Injection 的優缺點
優點:
1. 易於單元測試 
2. ??

缺點:
1. 所有的 function 必需先建立 Interface, 暫麻煩.
2. debug 時必需先 trace 到 interface 再 trace 到實際 implement 的 code.
More...
Bike, 2024/2/8 下午 04:38:17
.Net Framework 的檔案檢查機制 Web API 和 MVC 5
我們的目標是在啟動時,掛一個 global filter 來檢查上傳的檔案附檔名,避免上傳未預期的可執行檔。使用 global filter 可以防止程式設計師忘了做檔案檢查,發生危險。我們目前用到的 .Net Framework 有兩個類別,一個是 System.Web.Http.ApiController,另一個是 System.Web.Mvc.Controller,兩個要分開處理。

1. Web API (System.Web.Http.ApiController)
.Net Framework 的 Web API 2 在接收檔案時,必需使用 Request.Content.ReadAsMultipartAsync 把上傳的資料存入 MultipartMemoryStreamProvider 之後再來處理。
範例如下: 
    public class UploadController : ApiController
    {
        public async Task<object> PostFormData()
        {
            var provider = new MultipartMemoryStreamProvider();

            if (! Request.Content.IsMimeMultipartContent())
            {
                return "no file";
            }

            //要注意這裡的 await
            await Request.Content.ReadAsMultipartAsync(provider);

            foreach (var content in provider.Contents)
            {
                if (content.Headers.ContentDisposition.FileName != null)
                {
                    string localFilename = content.Headers.ContentDisposition.FileName.Replace("\"", "");
                    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(@"~/App_Data/Temp/"));
                    string filename = HttpContext.Current.Server.MapPath(@"~/App_Data/Temp/" + localFilename);
                    if (System.IO.File.Exists(filename))
                    {
                        System.IO.File.Delete(filename);
                    }

                    using (var fileStream = new FileStream(filename, FileMode.Create, FileAccess.Write))
                    {
                        var contentStream = await content.ReadAsStreamAsync();
                        await contentStream.CopyToAsync(fileStream);
                        Trace.WriteLine("Save To" + filename);
                    }
                }
            }
            return "OK";
        }
    }


程式碼中有個地方我沒有注意到。我一開始是用 Request.Content.ReadAsMultipartAsync(provider); 把資料讀進 provider,但前方沒有加上 await,造成有時讀不到檔案的情況,再次提醒自己 Async 和 Await 的關係。

直覺的想法是在 filter 中執行一樣的程式碼,不存檔,只要抓出檔名來檢查即可。但這時遇到一個問題 Request.Content.ReadAsMultipartAsync 不能執行兩次,Google 了一陣子,也沒找不到類似 seek(0) 的操作。所以只好自己寫一個暫存的機製。

這裡決定使用 System.Web.HttpContext.Current.Items 來暫存 provider,最後的 OnActionExecutingAsync 結果如下:

        /// <summary>
        /// 檔案檢查
        /// </summary>
        /// <param name="actionContext"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public override async Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
        {
            Trace.WriteLine("ApiCheckFile OnActionExecutingAsync");

            var request = actionContext.Request;
            if (!request.Content.IsMimeMultipartContent())
            {
                return;
            }

            var provider = new MultipartMemoryStreamProvider();
            await request.Content.ReadAsMultipartAsync(provider);

            //把 provider 存入 System.Web.HttpContext.Current.Items 之中,以便在 controller 中再度使用
            System.Web.HttpContext.Current.Items["MimeMultipartContentProvider"] = provider;

            foreach (var content in provider.Contents)
            {
                if (content.Headers.ContentDisposition.FileName != null)
                {
                    var filename = content.Headers.ContentDisposition.FileName.Replace("\"", "");
                    Trace.WriteLine(filename);

                    var ext = System.IO.Path.GetExtension(filename);
                    if (!".jpg,.jpeg,.png".Contains(ext.ToLower()))
                    {
                        throw new Exception("file format error.");
                    }
                }
            }

            return;
        }


而 controller 中的 Action 則改為以下的版本;本版本中,除了把上傳的檔案存檔以外,還有讀取 form data 中其它欄位的範例:

        public async Task<object> PostFormData()
        {
            //改由 HttpContext.Current.Items 中,讀取資料。
            MultipartMemoryStreamProvider provider = (MultipartMemoryStreamProvider)System.Web.HttpContext.Current.Items["MimeMultipartContentProvider"];

            //如果沒有經過 filter,provider會是 null, 這時就要直接由 Request.Content 讀入 provider
            if (provider == null)
            {
                provider = new MultipartMemoryStreamProvider();
                Request.Content.ReadAsMultipartAsync(provider);
            }

            foreach (var content in provider.Contents)
            {
                if (content.Headers.ContentDisposition.FileName != null)
                {
                    string localFilename = content.Headers.ContentDisposition.FileName.Replace("\"", "");
                    Trace.WriteLine("FileName: " + localFilename);
                    Trace.WriteLine("FileName: " + @"~/App_Data/Temp/" + localFilename);
                    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(@"~/App_Data/Temp/"));
                    string filename = HttpContext.Current.Server.MapPath(@"~/App_Data/Temp/" + localFilename);
                    if (System.IO.File.Exists(filename))
                    {
                        System.IO.File.Delete(filename);
                    }

                    using (var fileStream = new FileStream(filename, FileMode.Create, FileAccess.Write))
                    {
                        var contentStream = await content.ReadAsStreamAsync();
                        await contentStream.CopyToAsync(fileStream);
                        Trace.WriteLine("Save To" + filename);
                    }
                }
                else
                {
                    var contentStream = await content.ReadAsStreamAsync();
                    var reader = new System.IO.StreamReader(contentStream);
                    var data = reader.ReadToEnd();
                    Trace.WriteLine("data: " + data);
                }
            }
            return "OK";
        }


以上是展示 Web Api 的 Filter。

如果是 MVC 的 Controller,就簡單多了,直接讀取 actionContext.HttpContext.Request.Files 裡面各檔案的 FileName 即可。不過也遇到了一個和直覺不同的地方,對 actionContext.HttpContext.Request.Files 居然不能用 foreach 請見下方註解掉的地方。也許是我的用法有問題,如果有人找到可以使用的方法也麻煩告知。

        public override void OnActionExecuting(ActionExecutingContext actionContext)
        {
            Debug.WriteLine("MvcCheckFileFilter OnActionExecuting");
            if (actionContext.HttpContext.Request.Files.Count > 0)
            {
                for (int i = 0; i < actionContext.HttpContext.Request.Files.Count; i++)
                {
                    System.Web.HttpPostedFileBase file = actionContext.HttpContext.Request.Files[i];
                    if (System.IO.Path.GetExtension(file.FileName) != ".jpg")
                    {
                        throw new Exception("file format error.");
                    }
                    Debug.WriteLine(i + "MvcCheckFileFilter OnActionExecuting File type: " + file.FileName.ToString());
                }
            }

            //以下寫法會發生錯誤: 無法將類型 'System.String' 的物件轉換為類型 'System.Web.HttpPostedFileBase'。
            //foreach (HttpPostedFileBase file in actionContext.HttpContext.Request.Files)
            //{
            //    if (System.IO.Path.GetExtension(file.FileName) != ".jpg")
            //    {
            //        throw new Exception("file format error.");
            //    }
            //}
        }


最後是把 filter 掛在 global filter 裡,如下:
Web API Controller 的部份:
在 WebApiConfig.cs 裡加上 config.Filters.Add(new ApiCheckFile()); 見下圖:
 

附帶一提,Register 是在 global.asax 裡被叫用的。微軟的架構常常這樣,硬是拉到另一個目錄的獨立檔案裡,如果 global.asax 沒有這一行,不知所以的人,在 App_Start 裡,建立了一個 WebApiConfig.cs 然後會發現完全沒做用... 見下圖

 
MVC Controller 的部份,
在 FilterConfig.cs 中,加上 filters.Add(new MvcCheckFileFilter()); 如下圖
 

一樣是在 global.asax 中呼叫  FilterConfig.RegisterGlobalFilters,見下圖:

 
不過有趣的地方是,在 global.asax 裡, WebApiConfig.Register 和 FilterConfig.RegisterGlobalFilters 的叫用方法不同,一個是把 function 當作變數,一個是直接呼叫 function, 大家可以比較一下。

附註 1, 關於 OnActionExecutingAsync 和 OnActionExecuting:

Web API 的 filter 中,提供了 OnActionExecutingAsync 和 OnActionExecuting 兩個 method 可以 override ,我實驗的結果是如果兩個 method 都 override 了,只有 OnActionExecutingAsync 會被呼叫。

MVC 的 filter 中,只有 OnActionExecuting 可以 override。
 
More...
Bike, 2022/5/15 上午 10:01:11
ORM 的新範列
一些範列如下:

        //直接使用 Operator
        var products = ORM.Product.Select()
            .Where(CN.Product.Name == "ABC")
            .And(CN.Product.Name != "DEF")
            .And(CN.Product.Name % "ABC%") //這是 Like
            .And(CN.Product.Name | "apple, orange".SqlListStr()) // 這是 in
            .And(CN.Product.Is_Available)
            .And(!CN.Product.Is_Deleted)
            .And(CN.Product.OriginalPrice > 5)
            .And(CN.Product.OriginalPrice <= 500)
            .And(CN.Product.CreateDate < DateTime.Now.AddMonths(-1))
            .GetList<ORM.Product>();

//產出 SQL: Select * From [Product] (NoLock) Where ( ([Name] <> N'DEF') ) And ( ([Name] like N'ABC%') ) And ( ([Name] in ('apple',' orange')) ) And ([Is_Available] = 'Y') And ( ([Is_Deleted] = 'N') ) And ( ([OriginalPrice] > 5) ) And ( ([OriginalPrice] <= 500) ) And ( ([CreateDate] < '2020-11-26T10:17:15.553') )


        //用 Id 取出物件並修改
        var product = ORM.Product.Get(3);
        U2.WU.DebugWriteLine(product.Name);
        product.Name = "平格藍均抱枕套45*45 ABC";
        product.Modify();

        //新增一筆資料
        var newId = new ORM.Product()
        {
            Name = "New Product",
            OriginalPrice = 100,
            Is_Hot = "Y"
        }.Add();

        //用 Id 修改資料
        var updateCount = new ORM.Product(3)
        {
            Name = "New Product",
            OriginalPrice = 100,
            Is_Hot = "Y"
        }.Modify();

More...
Bike, 2020/12/26 下午 12:04:26
又一個字串合併惹的禍 AddPageDebugMessage
AddPageDebugMessage 造成購物車變慢.

因為有發現主要時間是花在 Coupon 的處理, 研突了半天, 覺得之前丟出來的 Debug 訊息太多, 所以我想把所有 coupon 處理時丟出來的 Debug 訊息關掉, 一個一個慢慢打開來看看哪一個步驟造成問題. 突然發現它就好了.

後來想想, 應該是因為我們把 Debug 訊息合併成大字串造成的, 這個花費的總時間會以 coupon 數量的平方或三次方的速度成長.  當 Coupon 的數量變多時, 花費的時間會成長的很快. 因為要夠多上線的 coupon 才會造成這個問題, 所以之前的測試都沒有發現這類的問題.

購物車中有用到 AddPageDebugMessage 請改成成使用  arraylist 的版本. 理論上會是固定時間, 另外還有做了一個開關, 要用定參數才會開啟 AddPageDebugMessage 的功能.
More...
Bike, 2018/11/12 下午 04:14:37
Ajax 的 Content Type
這兩天發現的現象。有點不好找錯,所以紀錄一下
因為制式報名頁面使用 ajax form 物件,但 ios 的 safari 一直發生資料有送出,
但是送出後網頁就不跑success後面的 javascript,例如彈跳訊息及導到下個頁面
一開始debug的方向有點猜錯,所以花了點時間找問題
後來才注意到,原來他跑到 ajax error去了,不是 ajax success
直覺可能是 ContentType 的問題,因為預設是 text/html
結果 Response.ContentType 改 application/x-javascript, 就過了  (WTF)
我猜 application/json 應該也沒問題吧
------------------------------
經查證: application/json 比較正確 



 
More...
darren, 2018/8/2 下午 12:33:16
zero-width space
寫程式這麼多年,終於被這個東西給害到,所以特別提一下
zero-width space: 就是沒有寬度的空白,字元碼  \u200b , 或是 urlencode =  %e2%80%8b
當你從 word , excel ,PDF 複製文字貼到記事本,網頁textbox, 或是 visual studio
有時候會把這個碼也一起貼上,重點是: 你肉眼根本看不出來

​2017-08-15 22:05:15​ -> 2017前面有 \u200b, 尾巴也有 
2017-08-15 22:05:15 -> 這個就正常

這會造成甚麼,DateTime.Parse 就會出錯,或是對字串做 MD5 hash 會造成錯誤的結果
然後就會一直 debug 找不出原因,要用 urlencode 測看看才會現出原形
另外,這個碼也無法用 Trim() 清掉,因為他不是 Char.IsWhiteSpace 成員

所以,從 word excel pdf 或是其他網頁 copy 文字貼到程式碼做測試
如果發生怪怪的bug,可能要思考一下是不是這個字元在作怪
More...
darren, 2018/7/19 下午 12:08:41
顯示錯誤位置的行數 MVC C# Error Line Number
https://stackoverflow.com/questions/628565/display-lines-number-in-stack-trace-for-net-assembly-in-release-mode/628590#628590

1. Go into the Properties window for the project where you want to see stack trace line numbers.
2. Click on the Build "vertical tab".
3. Select "Release" configuration. Check the DEBUG constant parameter.
4. Uncheck the "Optimize code" parameter to avoid the occasional trace issue with inlined code (this step is not essential).
5. Press the Advanced... button and choose Output -> Debug Info -> pdb-only.
6. Deploy the generated .pdb file with the assembly.

 
 
 
More...
Bike, 2018/4/9 上午 09:40:12
網站同時使用 C# 與 VB.net
由於早期網站都是VB.net寫的,若是直接換成 C#,就會耗費很多時間在轉換程式上
因此 ASP.NET 特別可以在同一網站同時寫 vb 跟 C#,方式是在 web.config compilation 加上設定
    <compilation debug="true" defaultLanguage="c#" targetFramework="4.0">
     <codeSubDirectories>
        <add directoryName="VB_Code"/>
        <add directoryName="CS_Code"/>
     </codeSubDirectories>
    </compilation>

也就是 VB.NET 的 code 就放到 ~\APP_Code\VB_Code 目錄
C# 的 code 就放到 ~\APP_Code\CS_Code 目錄
這樣做有兩點要注意
1.  Namespace 的命名,最好不要互相衝突, 要能夠區分出來
2.  VB_Code 與 CS_Code 放的位置有很大的影響, 因為牽涉到 compiler的先後順序,因為 VB_Code 在 CS_Code 在前面,所以 CS_Code可以叫用 VB_Code下的程式,但是 VB_Code 卻不能叫用 CS_Code 的程式,如果希望 VB_Code可以叫用 CS_Code的程式,就把設定換過來
    <compilation debug="true" defaultLanguage="c#" targetFramework="4.0">
     <codeSubDirectories>
        <add directoryName="CS_Code"/>
<add directoryName="VB_Code"/>
     </codeSubDirectories>
    </compilation>

缺點就是反過來 CS_Code不能使用 VB_Code的程式

基本上,若是舊的程式碼都在VB_Code 那就把 VB_Code 放到前面
More...
darren, 2017/5/10 下午 02:21:54
中文難字的繁簡轉換處理
看到黑暗有一個關於中文難字的繁簡轉換處理的文章, 先記錄部份在這裡.

http://blog.darkthread.net/post-2015-03-06-strconv-half-full-width-notes.aspx

      var ncrString = toNCR("黑暗執行緒犇ABC123");
      Debug.WriteLine(ncrString); //黑暗執行緒&#29319;ABC123
      var convString = Microsoft.VisualBasic.Strings.StrConv(
        ncrString, Microsoft.VisualBasic.VbStrConv.Narrow, 1028);
      Debug.WriteLine(convString); //黑暗执行绪&#29319;ABC123
      var resultString = fromNCR(convString);
      Debug.WriteLine(resultString); //黑暗执行绪犇ABC123


    static string toNCR(string input)
    {  
      StringBuilder sb = new StringBuilder();
      Encoding big5 = Encoding.GetEncoding("big5");
      foreach (char c in input)
      {
        //強迫轉碼成Big5,看會不會變成問號
        string cInBig5 = big5.GetString(big5.GetBytes(new char[] {c}));
        //原來不是問號,轉碼後變問號,判定為難字
        if (c!='?' && cInBig5=="?")
          sb.AppendFormat("&#{0};", Convert.ToInt32(c));
        else
          sb.Append(c);
      }
      return sb.ToString();
    }
 
    static string fromNCR(string input)
    {
      return Regex.Replace(input, "&#(?<ncr>\\d+?);", (m) =>
      {
        return Convert.ToChar(int.Parse(m.Groups["ncr"].Value)).ToString();
      });
    }
More...
Bike, 2016/11/21 下午 12:40:54
facebook 網頁分享 Debug 模式
當我們網站裡的某個網址要分享到 facebook 時,
facebook 會主動到我們網頁擷取內容,然後存在cache裡
facebook 給開發人員一個頁面可以測試看看結果
https://developers.facebook.com/tools/debug/og/object/ 
可以貼上自己網站的某個網址 ex.
http://www.shopunt.com/eng/unreal-touch-mineral-powder-blush/p/1129/c/34
就可以看到 facebook 爬到的結果,如果上次爬的是很久以前,這個地方也可以重新爬一次

----------------------------------------------------------------
經由測試結果,發現這功能出現的圖片,跟實際上在網站裡點fb分享出現的內容還是有差異
想出現的圖片還是不能控制,根據[此文章]說明
要把 og: 所有屬性都加上才行
header 圖片部分最好再加上
<link href="圖片連結網址" rel="image_src" type="image/jpeg">

應該就能保證分享圖片是自己想要的。 --> 這有空再來測試好了
 
More...
darren, 2014/8/13 下午 07:32:59
|< 12 >|
頁數 1 / 2 下一頁
~ Uwinfo ~