GooglePrettify

2019年2月11日 星期一

Using dynamic SQL to handle multiple optional parameters

Previously I mentioned a way to handle stored procedures with multiple optional parameters, that of the recompile hint. That's fine in many cases but since it prevents plan caching for that query, it can result in higher CPU usage, This may can be unacceptable if the procedure is called very frequently or if the server is already under CPU load.
For those cases, converting the procedure to use dynamic SQL may be a better solution.
Let's start with the same example as last time
1
SELECT ProductID, 
2
    ReferenceOrderID, 
3
    TransactionType, 
4
    Quantity,
5
    TransactionDate, 
6
    ActualCost 
7
FROM Production.TransactionHistory
8
WHERE (@ProductID IS NULL OR ProductID = @ProductID)
9
    AND (@OrderStatus IS NULL OR OrderStatus = @OrderStatus)
10
    AND (@OrderTotal IS NULL OR OrderTotal >= @OrderTotal)
11
    AND (@RegionID IS NULL OR Region = @RegionID);
When using Dynamic SQL, there is one very important requirement. User input must NOT be concatenated into a string that will be executed. Doing so causes SQL injection vulnerabilities. SQL Injection has been the cause of a number of high-profile data breaches recently.
Fortunately, concatenating input into the string isn't necessary (it's the easy way, hence why so much of it is seen). Dynamic SQL can be parameterised.
Firstly, the variables and the initial portion of the select statement

1
DECLARE @SQL NVARCHAR(4000), @Where NVARCHAR(4000) = ''
2
SET @SQL = 'SELECT ProductID, ReferenceOrderID, TransactionType, Quantity, TransactionDate, ActualCost
3
from Production.TransactionHistory '
The variables do need to be nvarchar.
For each of the parameters which may or may not be passed, an IF block checks whether or not to add that predicate to the where clause

1
IF (@Product IS NOT NULL)
2
    SET @Where = @Where + 'AND ProductID = @_Product '
3
IF (@OrderID IS NOT NULL)
4
    SET @Where = @Where + 'AND ReferenceOrderID = @_OrderID '
5
IF (@TransactionType IS NOT NULL)
6
    SET @Where = @Where + 'AND TransactionType = @_TransactionType '
7
IF (@Qty IS NOT NULL)
8
    SET @Where = @Where + 'AND Quantity = @_Qty '
Note the use of new parameters inside the dynamic SQL. The values which are being checked are not being added to the string.
You can start the where clause off with WHERE 1=1 AND ..., but I personally dislike that pattern, I rather do this
1
IF (LEN(@Where) > 0)
2
    SET @SQL = @SQL + 'WHERE ' + RIGHT(@Where, LEN(@Where)-3)
Now we have a dynamic SQL string which just contains the predicates that are actually going to filter the data. All that's left is to execute it. This is done with the sp_executeSQL system procedure, allowing for parameters to be passed to the dynamic string.
The first parameter to sp_executeSQL is the string to be executed. The second is the parameter list, the third onwards assigns values to the parameters
1
EXEC sp_executesql @SQL,
2
    N'@_Product int, @_OrderID int, @_TransactionType char(1), @_Qty int',
3
    @_Product = @Product, @_OrderID = @OrderID, @_TransactionType = @TransactionType, @_Qty = @Qty

from : https://yoda.entelect.co.za/view/3279/using-dynamic-sql-to-handle-multiple-optional-parameters

2018年12月26日 星期三

[C#.NET] 字串 codepage 轉碼處理

這是我在某天所遇到的一個問題,我對某台設備進行操作時它回傳了一串我看不懂的字串
⊃;nÅé¼Ò⊃;Õ¤¤ªº¤@¯ë©Ê¿ù»~¡G¼Ð·Ç GUI (⊃;ϧΤƥΤᤶ­±)¡C";
當時直覺就是使用編碼來處理,不過這樣做並不會得到正確的結果,原因是我並未取得正確的編碼byte,也就是codepage
byte[] big5 =Encoding.GetEncoding("Big5").GetBytes("⊃;nÅé¼Ò⊃;Õ¤¤ªº¤@¯ë©Ê¿ù»~¡G¼Ð·Ç GUI (⊃;ϧΤƥΤᤶ­±)¡C");
Console.WriteLine(Encoding.GetEncoding("Big5").GetString(big5));
 
插撥一下,稍微講解一下Encoding.GetEncoding的用法,Encoding.GetEncoding的第一個參數叫codepage,什麼叫codepage(字碼頁)
image
字碼頁。
微軟賦予每個語言一個數字代碼,叫做字碼頁(codepage)。字碼頁可能會決定使用哪些文字,以及單位符號等等。
繁體中文的字碼頁是 950。
我們可以由Encoding.GetEncodings方法 加上  Encoding.CodePage 屬性 取得所有的codepage
static void codepage()
{
    foreach (EncodingInfo ei in Encoding.GetEncodings())
    {
        Encoding e = ei.GetEncoding();
        Console.WriteLine("Name:{0},CodePage:{1}",ei.Name, e.CodePage);
    }
    Console.ReadLine();
}
image
也可以查一下google


接下來回到正題,該怎麼樣處理那該死的亂碼?只要用以下的原始碼就能夠處理。
static void encoding()
{
    string source = "⊃;nÅé¼Ò⊃;Õ¤¤ªº¤@¯ë©Ê¿ù»~¡G¼Ð·Ç GUI (⊃;ϧΤƥΤᤶ­±)¡C";
    byte[] unknow = Encoding.GetEncoding(28591).GetBytes(source);
    string Big5 = Encoding.GetEncoding(950).GetString(unknow);
    Console.WriteLine(Big5);
    Console.ReadLine();
}
先把字串轉成正確的byte
byte[] unknow = Encoding.GetEncoding(28591).GetBytes(source);
再把轉到你想要顯示的編碼
string Big5 = Encoding.GetEncoding(950).GetString(unknow);

果真翻譯成我們要看的編碼了~
image


好了問題來了,怎麼知道編碼是28591,我們可以用下列片斷程式碼來處理,會得到所有codepage交叉處理的結果,觀察文字檔有哪些是看的懂的文字,會得到不少的正確。

static void savecode()
{
    StringBuilder sb = new StringBuilder();
    string source = "⊃;nÅé¼Ò⊃;Õ¤¤ªº¤@¯ë©Ê¿ù»~¡G¼Ð·Ç GUI (⊃;ϧΤƥΤᤶ­±)¡C";

    foreach (var e1 in  Encoding.GetEncodings())
    {
        foreach (var e2 in Encoding.GetEncodings())
        {
            byte[] unknow = Encoding.GetEncoding(e1.CodePage).GetBytes(source);
            string result = Encoding.GetEncoding(e2.CodePage).GetString(unknow);
            sb.AppendLine(string.Format("{0} => {1} : {2}",e1.CodePage,e2.CodePage,result));
        }
    }
    File.WriteAllText("test.txt", sb.ToString());
}
image

內容有1.8Mbyte實在很多,這次只要用950跟所有的codepage交叉比對,資料量立即下降許多
static void savebig5()
{
    StringBuilder sb = new StringBuilder();
    string source = "⊃;nÅé¼Ò⊃;Õ¤¤ªº¤@¯ë©Ê¿ù»~¡G¼Ð·Ç GUI (⊃;ϧΤƥΤᤶ­±)¡C";

    foreach (var e in Encoding.GetEncodings())
    {
        byte[] unknow = Encoding.GetEncoding(e.CodePage).GetBytes(source);
        string result = Encoding.GetEncoding(950).GetString(unknow);
        sb.AppendLine(string.Format("{0} => {1} : {2}", e.CodePage, 950, result));
    }
    File.WriteAllText("big5.txt", sb.ToString());
}
image


後記:
也感謝所有參與回覆的伙伴。
若有謬誤,煩請告知,新手發帖請多包涵

from : https://dotblogs.com.tw/yc421206/archive/2011/06/09/27596.aspx

Encoding of C# (CLR)

A string in C# is always UTF-16

If request from website is using UTF-8, you will always need to do the conversion from UTF-16 to UTF-8 as below:
public static string Utf16ToUtf8(string utf16String)
{
    // Get UTF16 bytes and convert UTF16 bytes to UTF8 bytes
    byte[] utf16Bytes = Encoding.Unicode.GetBytes(utf16String);
    byte[] utf8Bytes = Encoding.Convert(Encoding.Unicode, Encoding.UTF8, utf16Bytes);

    // Return UTF8 bytes as ANSI string
    return Encoding.Default.GetString(utf8Bytes);
}

2018年12月18日 星期二

C# 存取修飾詞 - internal

遇過不少 .NET 工程師,都知道 C# 存取修飾詞有四種,public、protected、private及internal。
前三種大部都可以很輕易的回答出來,但知道internal的工程師比例卻不高。
本篇來幫大家複習一下 C# 的存取修飾詞 internal。

存取範圍

internal的存取範圍是相同組件(Assembly)都可以使用,白話一點講就是internal可以在同一個dll內存取。
  • 類別預設的存取修飾詞是 internal。
  • 類別成員預設的存取修飾詞是 private。

protected internal

internal可以跟protected何在一起使用,存取範圍就變成:
相同組件 或 子類別都可以存取。
如下範例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
namespace AssemblyA
{
    class Parent
    {
        protected internal int Number;
    }

    class Sample
    {
        public void Method()
        {
            var parent = new Parent();
            // 因為 Number 帶有 internal,所以沒繼承也能存取
            parent.Number = 10; 
        }
    }
}

namespace AssemblyB
{
    class Child : AssemblyA.Parent
    {
        public void Method()
        {
          // 因為 Number 帶有 protected,所以在不同組建也能存取
            Number = 20;
        }
    }
}

Friend Assembly

為了符合封裝原則,基本上我們不太希望把不該開放的類別或成員給外部的組件存取,但為了測試專案,不開放存取權限又顯得很難做事。
這時候我們可以透過 InternalsVisibleTo 開放特定的組件也能存取internal修飾詞的類別或成員。
例如我們有 AssemblyA 及 AssemblyA.Tests 專案,我們希望 AssemblyA.Tests 專案可以存取 AssemblyA 專案的internal類別或成員。
打開 AssemblyA 專案底下的 Properties\AssemblyInfo.cs 檔案編輯:
C# 存取修飾詞 - internal Friend Assembly
1
2
3
4
5
using System.Runtime.CompilerServices;

//...

[assembly: InternalsVisibleTo("AssemblyA.Tests")]
以上設定並不是把 AssemblyA 及 AssemblyA.Tests 變成同組件,而是:
AssemblyA.Tests 可以存取 AssemblyA 的internal類別及成員。
AssemblyA 依然不可以存取 AssemblyA.Tests 的internal類別及成員。

參考



from : https://blog.johnwu.cc/article/c-sharp-access-modifiers-internal.html