顯示具有 C# 標籤的文章。 顯示所有文章
顯示具有 C# 標籤的文章。 顯示所有文章

2022年1月13日 星期四

[工具] WebService測試工具SoapUI

 

 關於使用SoapUI來測試WebService的筆記





貼上網址,後一定要加上 ?WSDL







 

用<![CDATA[   ]]>包覆電文內容,但頭尾都不能換行哦


 






2021年9月1日 星期三

[MSSQL] 預存程序引用DLL參考



*在組件中加入DLL參考



*可將DLL檔案轉成bytes 直接加入參考



CREATE ASSEMBLY SQLCom

FROM 0x4D5A900003.................

WITH PERMISSION_SET = SAFE;



DLL to bytes string 參考

https://stackoverflow.com/questions/2885335/clr-sql-assembly-get-the-bytestream





 *DLL程式碼


    [Microsoft.SqlServer.Server.SqlFunction]

    public static string GZip(string rawString)

    {

       ..................

            return (string)(Convert.ToBase64String(zippedData));

    }








    * 於資料新增 擴充的 預存程序

    CREATE FUNCTION dbo.GZip(@src nvarchar(MAX))

    RETURNS nvarchar(MAX)

    EXTERNAL NAME SQLCom.UserDefinedFunctions.GZip





*SQL指令
    SELECT dbo.GZip(S_String)




2019年4月4日 星期四

[C#] 用CLR讓 SQL 可以用GZIP壓縮字串


C#  程式碼







     
        /// <summary>
        /// 将传入字符串以GZip算法压缩后,返回Base64编码字符
        /// </summary>
        /// <param name="rawString">需要压缩的字符串</param>
        /// <returns>压缩后的Base64编码的字符串</returns>
        public static string GZip(string rawString)
        {
            return rawString;   //off test
            if (string.IsNullOrEmpty(rawString) || rawString.Length == 0)
            {
                return "";
            }
            else
            {
                byte[] rawData = System.Text.Encoding.UTF8.GetBytes(rawString.ToString());
                byte[] zippedData = GZip_Compress(rawData);
                return (string)(Convert.ToBase64String(zippedData));
            }

        }
        /// <summary>
        /// GZip压缩
        /// </summary>
        /// <param name="rawData"></param>
        /// <returns></returns>
        public static byte[] GZip_Compress(byte[] rawData)
        {
            MemoryStream ms = new MemoryStream();
            GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Compress, true);
            compressedzipStream.Write(rawData, 0, rawData.Length);
            compressedzipStream.Close();
            return ms.ToArray();
        }
        /// <summary>
        /// 将传入的二进制字符串资料以GZip算法解压缩
        /// </summary>
        /// <param name="zippedString">经GZip压缩后的二进制字符串</param>
        /// <returns>原始未压缩字符串</returns>
        public static string UnGZip(string zippedString)
        {
            return zippedString;   //off test
            if (string.IsNullOrEmpty(zippedString) || zippedString.Length == 0)
            {
                return "";
            }
            else
            {
                byte[] zippedData = Convert.FromBase64String(zippedString.ToString());
                return (string)(System.Text.Encoding.UTF8.GetString(UnGZip_Decompress(zippedData)));
            }
        }
        /// <summary>
        /// ZIP解压
        /// </summary>
        /// <param name="zippedData"></param>
        /// <returns></returns>
        public static byte[] UnGZip_Decompress(byte[] zippedData)
        {
            MemoryStream ms = new MemoryStream(zippedData);
            GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Decompress);
            MemoryStream outBuffer = new MemoryStream();
            byte[] block = new byte[1024];
            while (true)
            {
                int bytesRead = compressedzipStream.Read(block, 0, block.Length);
                if (bytesRead <= 0)
                    break;
                else
                    outBuffer.Write(block, 0, bytesRead);
            }
            compressedzipStream.Close();
            return outBuffer.ToArray();
        }
 







產生SQL共用函式

-----------------------1.set SQL Server可執行CLR-----------------------
sp_configure 'clr enabled', 1
GO
RECONFIGURE
go

-----------------------2.建立ASSEMBLY-----------------------

CREATE ASSEMBLY Net_SQLCom  FROM '******\bin\Debug\SQLCom.dll'
WITH PERMISSION_SET = SAFE;
--drop ASSEMBLY Net_SQLCom
go

--chk  有沒有看到Net_SQLCom
SELECT * FROM sys.assemblies
go

-----------------------3.建立function-----------------------
--drop function GZip
--drop function UnGZip

CREATE FUNCTION [dbo].[GZip](@str [nvarchar](max) )
RETURNS [nvarchar](MAX) WITH EXECUTE AS CALLER
AS
EXTERNAL NAME [Net_SQLCom].[UserDefinedFunctions].[GZip]
GO


CREATE FUNCTION [dbo].[UnGZip](@str [nvarchar](max) )
RETURNS [nvarchar](MAX) WITH EXECUTE AS CALLER
AS
EXTERNAL NAME [Net_SQLCom].[UserDefinedFunctions].[UnGZip]
GO

--chk  有沒有看到function
SELECT * FROM sys.assembly_modules;

-----------------------4.Test-----------------------
select [dbo].[UnGZip]([dbo].[GZip]('setse' ))





注意資料庫型別

char資料有固定長度,並且都為英文數字。
nchar資料有固定長度,但不確定是否皆為英文數字。
varchar資料沒有固定長度,並且都為英文數字。
nvarchar資料沒有固定長度,且不確定是否皆為英文數字。

[C#] 產生DLL給MS SQL引用



建置CLR 使用者定義函式,產出DLL給MS SQL 會出現錯誤

CREATE ASSEMBLY 失敗,因為組件是針對不支援的 Common Language Runtime 版本所建立的

此時可使用  .NET  3.5 編譯即可



環境 VS 2015
MS SQL 2008 R2


CLR建置方法參考:

如何在SQL Server中加入 C# CLR Function:
https://www.uuu.com.tw/Public/content/article/18/20180402.htm

https://dotblogs.com.tw/rockchang/2016/06/07/141319




2019年1月1日 星期二

[C#] 取得檔案路徑相關資訊



參考:http://rojerchen.blogspot.com/2013/02/c.html


            string file = @"d:\abc\123.txt";

            //string file = @"d:\abc\";

            string s0 = Path.GetFileName(file); //取得完整檔名 > 123.txt

            string s1 = Path.GetFileNameWithoutExtension(file); //取得檔案名,不包含副檔名,本例得到 123
           
            string s2 = Path.GetExtension(file); //取得副檔名 txt

            string s3 = Path.GetPathRoot(file); //取得根目錄 d:\a

            string s4 = Path.GetFullPath(file); //取得路徑 d:\abc\123.txt



2017年12月12日 星期二

[C#] 編碼問題,把所有的編碼都跑過一輪


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



    foreach (EncodingInfo ei in Encoding.GetEncodings())
    {
        Encoding e = ei.GetEncoding();
        Console.WriteLine("Name:{0},CodePage:{1}",ei.Name, e.CodePage);
    }




轉自 https://goo.gl/Xgh24y

重新解碼在編碼,以解決亂碼問題

StringBuilder sb = new StringBuilder();
string source = "hello 浣犲ソ";
 
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());


2016年10月17日 星期一

[C#] 取得網址 Using Request.Url to find specific parts of the web page's URL



參考:http://www.codepal.co.uk/show/Using_RequestUrl_to_find_specific_parts_of_the_web_pages_address




Request.Url.GetLeftPart(UriPartial.Authority) http://www.codepal.co.uk:123
Request.Url.GetLeftPart(UriPartial.Path) http://www.codepal.co.uk:123/RequestUri.aspx
Request.Url.GetLeftPart(UriPartial.Query) http://www.codepal.co.uk:123/RequestUri.aspx?queryStringVal=Hello
Request.Url.GetLeftPart(UriPartial.Scheme) http://
Request.Url.ToString http://www.codepal.co.uk:123/RequestUri.aspx?queryStringVal=Hello
Request.Url.AbsolutePath /RequestUri.aspx
Request.Url.AbsoluteUri http://www.codepal.co.uk:123/RequestUri.aspx?queryStringVal=Hello
Request.Url.Authority www.codepal.co.uk:123
Request.Url.GetComponents(UriComponents.AbsoluteUri, UriFormat.SafeUnescaped) http://www.codepal.co.uk:123/RequestUri.aspx?queryStringVal=Hello
Request.Url.GetComponents(UriComponents.Fragment, UriFormat.SafeUnescaped)
Request.Url.GetComponents(UriComponents.Host, UriFormat.SafeUnescaped) www.codepal.co.uk
Request.Url.GetComponents(UriComponents.HostAndPort, UriFormat.SafeUnescaped) www.codepal.co.uk:123
Request.Url.GetComponents(UriComponents.HttpRequestUrl, UriFormat.SafeUnescaped) http://www.codepal.co.uk:123/RequestUri.aspx?queryStringVal=Hello
Request.Url.GetComponents(UriComponents.KeepDelimiter, UriFormat.SafeUnescaped)
Request.Url.GetComponents(UriComponents.Path, UriFormat.SafeUnescaped) RequestUri.aspx
Request.Url.GetComponents(UriComponents.PathAndQuery, UriFormat.SafeUnescaped) /RequestUri.aspx?queryStringVal=Hello
Request.Url.GetComponents(UriComponents.Port, UriFormat.SafeUnescaped) 123
Request.Url.GetComponents(UriComponents.Query, UriFormat.SafeUnescaped) queryStringVal=Hello
Request.Url.GetComponents(UriComponents.Scheme, UriFormat.SafeUnescaped) http
Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.SafeUnescaped) http://www.codepal.co.uk:123
Request.Url.GetComponents(UriComponents.SerializationInfoString, UriFormat.SafeUnescaped) http://www.codepal.co.uk:123/RequestUri.aspx?queryStringVal=Hello
Request.Url.GetComponents(UriComponents.StrongAuthority, UriFormat.SafeUnescaped) www.codepal.co.uk:123
Request.Url.GetComponents(UriComponents.StrongPort, UriFormat.SafeUnescaped) 123
Request.Url.Host www.codepal.co.uk
Request.Url.HostNameType.ToString Dns
Request.Url.OriginalString http://www.codepal.co.uk:123/RequestUri.aspx?queryStringVal=Hello

2016年4月7日 星期四

[c#] (413) Request Entity Too Large


轉自:http://karatejb.blogspot.tw/2015/04/troubleshooting-wcf-error-413-request.html


使用wcf服務時出現以下錯誤

(413) Request Entity Too Large

原來是WCF預設單筆Message size 為65KB, 避免DOS攻擊。
當超過此上限時,便會引發此錯誤。
這時候需再client端和wcf服務端的config加上以下設定


WCF的Config檔
<configuration>
<system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding maxReceivedMessageSize="2147483647"
                 maxBufferSize="2147483647"
                 maxBufferPoolSize="2147483647">
          <readerQuotas maxDepth="32"
                        maxArrayLength="2147483647"
                        maxStringContentLength="2147483647"/>
        </binding>
      </basicHttpBinding>
    </bindings>
</system.serviceModel>
</configuration>



Client的Config檔

<configuration>
<system.serviceModel>

      <bindings>
          <basicHttpBinding>
              <binding name="BasicHttpBinding_IMonitorService"
                        maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647"receiveTimeout="00:30:00" sendTimeout="00:30:00"/>
          </basicHttpBinding>
          <netNamedPipeBinding>
              <binding name="NetNamedPipeBinding_IMonitorService">
                  <security mode="None" />
              </binding>
          </netNamedPipeBinding>
       
      </bindings>
</system.serviceModel>
</configuration>



2016年3月22日 星期二

[C#] NLog 建置筆記






        /// <summary>
        /// NLog 紀錄
        /// </summary>
        public static NLog.Logger NLogger = NLog.LogManager.GetCurrentClassLogger();





* 抓取Session的值

參考 https://github.com/NLog/NLog/wiki/AspNetSession-layout-renderer

程式:
Session["user"] = new UserInfo { Name= "johnDoe", Id = 100};

nlog config設定 :
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <targets>
        <target name="logfile" xsi:type="File" fileName="file.txt" />
    </targets>

    <rules>
        <logger name="*" minlevel="Info" writeTo="logfile" layout="${aspnet-session:Variable=User.Name:EvaluateAsNestedProperties=true}/>
    </rules>
</nlog>



發生【LayoutRenderer cannot be found: 'aspnet-request'】的錯誤時,
需安裝 NLog.Extended.dll 可擴增功能
http://kevintsengtw.blogspot.tw/2011/10/nlog-advanced-net-logging-3.html




Session格式範例
http://nlog-project.org/documentation/v2.0.1/html/T_NLog_LayoutRenderers_AspNetSessionValueLayoutRenderer.htm


You can set the value of an ASP.NET Session variable by using the following code:

C#
HttpContext.Current.Session["myvariable"] = 123;
HttpContext.Current.Session["stringvariable"] = "aaa BBB";
HttpContext.Current.Session["anothervariable"] = DateTime.Now;


Example usage of ${aspnet-session}:

${aspnet-session:variable=myvariable} - produces "123"
${aspnet-session:variable=anothervariable} - produces "01/01/2006 00:00:00"
${aspnet-session:variable=anothervariable:culture=pl-PL} - produces "2006-01-01 00:00:00"
${aspnet-session:variable=myvariable:padding=5} - produces "  123"
${aspnet-session:variable=myvariable:padding=-5} - produces "123  "
${aspnet-session:variable=stringvariable:upperCase=true} - produces "AAA BBB"



常用的:
${time} 時間
${asp-session:variable=String}  Session
${aspnet-request:cookie=String:serverVariable=String:queryString=Strin:item=String:form=String}
Cookie_ queryString

${basedir} 根目錄
${date} 日期+時間
${level} log等級
${newline} 換行
${shortdate} yyyy-MM-dd 日期

請參考 https://github.com/nlog/NLog/wiki/Layout%20Renderers


-------------------------------------


NLog config設定的變數宣告方式:

${APName}_${mdc:item=DateName}


程式碼:

            //以時間來命名 NLog 檔名,需在NLog.config 宣告 ${mdc:item=DateName} 變數來使用
            NLog.MappedDiagnosticsContext.Set("DateName", DateTime.Now.ToString("HH-mm-ss"));





2015年11月17日 星期二

[C#] 善用DEBUG模式


善用DEBUG狀態下才執行的程式碼來做開發偵錯



在Web.config裡頭定義
    <compilation debug="true" targetFramework="4.5" />


在程式碼裡面用

#if DEBUG

#endif


或是

if (HttpContext.Current.IsDebuggingEnabled)
{

}



from:http://blog.miniasp.com/post/2009/09/16/How-to-utilize-Debug-mode-to-develop-aspnet-and-other-net-applications.aspx

http://www.dotnetperls.com/isdebuggingenabled

2015年9月4日 星期五

移除 XML 中 namespace 方法



Form: http://jesily-tw.blogspot.tw/2014/07/xml-namespace.html


移除 XML 中 namespace 方法

      //Implemented based on interface, not part of algorithm
        public  string RemoveAllNamespaces(string xmlDocument)
        {
            XElement xmlDocumentWithoutNs = RemoveAllNamespaces(XElement.Parse(xmlDocument));

            return xmlDocumentWithoutNs.ToString();
        }

        //Core recursion function
        private  XElement RemoveAllNamespaces(XElement xmlDocument)
        {
            if (!xmlDocument.HasElements)
            {
                XElement xElement = new XElement(xmlDocument.Name.LocalName);
                xElement.Value = xmlDocument.Value;

                foreach (XAttribute attribute in xmlDocument.Attributes())
                    xElement.Add(attribute);

                return xElement;
            }
            return new XElement(xmlDocument.Name.LocalName, xmlDocument.Elements().Select(el => RemoveAllNamespaces(el)));
        }

2015年7月11日 星期六

Fortify的資料流分析技術



Fortify的資料流分析技術

Fortify SCA引入了類似taint mode的概念,工具會以污染標示元(taint flag)自動標示出受污染的變數源,稱為Source,這個污染源通常是網頁的輸入或是程式參數輸入點,變數經過一連串的傳遞,到達可能會引發真正安全風險的函式呼叫,稱為Sink,也就是事件的引爆點。





來自:http://www.gss.com.tw/index.php/focus/eis/44-eis59/122-fortify

2015年6月12日 星期五

[MVC] 瘋狂發送了一堆 arterySignalR/poll 的 request



.NET MVC 會瘋狂發這種Request

How do I stop ASP.NET from sending 1000 poll requests 

GET http://localhost:56832/1c71cd8404f34693989ae85105c388c8/arterySignalR/poll?transport=longPolling&connectionToken=AQAAANCMnd8BFdERjHoAwE%2FCl%2BsBAAAAP5q4VI1aYkG73Qjc15vRQAAAAAACAAAAAAAQZgAAAAEAACAAAACYD3vHvvsQBcyldpAbdPD%2B%2FXCqmKwQPh%2FPCYkUWpNuHwAAAAAOgAAAAAIAACAAAAArGFNrtbAKafl4Zza50Znndit9CUb%2FUxL7ZkSDgLfspzAAAAC7bxQMEUafPkIyJdXrWuizotO3bxDf%2BGRZYi07dJ8pjqbSXOGxJmrQhx3GTVzP6hRAAAAADKmJ6J1amG5ZuCqfWkbGvFl3yHO9kgZdmIt6TmjYakLQepTUUzZlTsoyiUWz6VVJZ4HgMjkEpNRMpqrlO5QDcA%3D%3D&messageId=d-5AC8B2C-CA%2C0%7CCH%2C3%7CCI%2C0&requestUrl=http%3A%2F%2Flocalhost%3A58119%2FDefault.aspx&browserName=Firefox&tid=0&_=1386850842869 HTTP/1.1
Host: localhost:56832
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0
Accept: text/plain, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://localhost:58119/Default.aspx
Origin: http://localhost:58119
Cookie: ASP.NET_SessionId=2hpyrlt5epkatwwkil2chwzt
Connection: keep-alive




  • In the Web.config file, add a key named “vs:EnableBrowserLink” with the value “false” in the appSettings section.
    <appSettings>
      <add key="vs:EnableBrowserLink" value="false"/>
    </appSettings>
          


form http://www.asp.net/visual-studio/overview/2013/using-browser-link#disabling



http://blog.darkthread.net/post-2014-02-11-browserlink-break-onbeforeunload-in-firefox.aspx




 

MangoHost Copyright © 2009 Cookiez is Designed by Ipietoon for Free Blogger Template