/* by josh */

2014年10月8日 星期三

[MSQL] 釋放MSSQL Server Cache (緩衝集區裡沒有足夠的可用記憶體)

當出現"緩衝集區裡沒有足夠的可用記憶體"此項錯誤時,可嘗試使用以下指令釋放快取記憶體;或是於程式中固定一段時間執行此三個Query

操作指令(適用2005,2008):
DBCC FREESYSTEMCACHE('all')
DBCC FREESESSIONCACHE
DBCC FREEPROCCACHE WITH NO_INFOMSGS

2014年9月22日 星期一

[WCF] 建立net.tcp之WCF服務

以下示範如何建立一個使用net.tcp協定的WCF server
其中合約定義在IFileRepositoryService.cs
而合約內容實作在FileRepositoryService.cs


步驟1.設定服務內容(於App.config中點選右鍵->編輯WCF組態)


  • 設定服務的名稱及服務所使用的行為名稱
  • 在主機中加入net.tcp的服務位址
    



  • 新增端點並將端點類型設為netTcpBinding,另外需指定合約名稱
        
步驟2.新增一個類型為netTCPBinding的繫結(Binding),並設定繫結各項參數


步驟3.於[進階].[服務行為]中新增一個服務行為(serviceBehavior);且因為使用net.tcp的關係,此處必須新增一個serviceMetadata用來給SvcUtil.exe產生Proxy

  • serviceMetada中必須將HttpGetEnabled改為True;並且於HttpGetUrl中指定SvcUtil.exe去找尋服務的位址,此處不可與WCF net.tcp 服務使用同一個port



步驟4.程式中撰寫開啟服務的程式碼

 ServiceHost host;
 FileRepositoryService service;
 service = new FileRepositoryService();
 host = new ServiceHost(typeof(FileRepositoryService));
            
            
 host.Faulted += new EventHandler(Host_Faulted) 
 try
 {
    host.Open();
 }

其中ServiceHost位於System.ServiceModel命名空間中

程式執行後便可在SvcUtil中利用serviceMetadata中的服務位址去產生Proxy檔案及client的.config檔案

之後便可於Client端程式中加入此cs檔案並且利用此class新增wcf物件,而Client端的.config則使用output.config中的內容即可

2014年7月14日 星期一

[C#] 多執行緒互斥存取

使用多執行緒執設計的程式有可時會面臨到同一時間不同執行緒會存取同一檔案的情況,此時.NET會跳出由於另一個處理序正在使用檔案…”的例外。

若要避免此情況可使用C#的關鍵字”lock”;在lock區塊中的程式碼被某一個執行緒A占用時,若有其他執行緒B要執行,則必須等到執行緒A離開此區塊後,執行緒B才可進入。


For example
假設有一個Backgroundworker不斷寫入log如下圖:


void BackGroundWorker_writeLog(object sender,DoWorkEventArgs e)
{
 while (true)
 {
               lock (thisLock)
               {
                    objSystemEventLogShow.Show("背景執行緒   "+counter, false);
                    counter++;
               }
 }
}

主執行緒中另一個timer也會寫入log,如下:

private void timer1_Tick(object sender, EventArgs e)
        {
            lock (thisLock)
            {
                objSystemEventLogShow.Show("主執行緒   " + counter, true);
                counter = 1;
            }
        }

因為backgroundworker所產生的執行緒不斷地在寫log,若於backgroundworker正在寫入時,主執行緒timer正好被觸發且要寫入同一個檔案,此時便會產生例外造成程式終止。

為了避免此情況,可在寫log時的取塊中可以加入lock關鍵字;而lock()中的參數則可以想像成是一個mutex,執行緒需取得存取權才能進入函式中,函式執行完畢則釋放存取權。


所以,號誌應該被宣告為全域變數,且最好是靜態的(static)。此例中我在class開頭便做宣告,如下圖:


需要注意的是,Lock的位置必須放對,以上面的例子而言,如果將lock放在while(true)的外面,while迴圈不斷地執行,換句話說backgroundworker並不可能釋放log的資源,如此主執行緒timer將永遠等不到資源可以執行,如此便造成執行緒飢餓(starvation)。如下:

void BackGroundWorker_writeLog(object sender,DoWorkEventArgs e)
        {
            lock (thisLock)
            {
                while (true)
                {
                    objSystemEventLogShow.Show("背景執行緒   " + counter, false);
                    counter++;

                }
            }
        }

2014年3月26日 星期三

[C#] .NET Compact Framework 3.5之WCF 使用說明

微軟已在 .net compact framework 3.5版中加入了WCF client的功能(但並未支援WCF server);
要在.net compact framework上使用wcf service必須用到Power Toys for .NET Compact Framework 3.5中的ServiceModel Metadata Tool for the .NET Compact Framework (NetCFSvcUtil)程式來產生Proxies藉以呼叫WCF service。
注意:若你是使用Windows 7以上的OS開發,務必下載支援windows 7的NetCFSvcUtil,否則無法正確產生proxies

以下說明如何建立service及client,

Server端:
Step 1: 新增合約IGreetingService.cs,此例之合約名稱為IGreetingService

namespace WcfDemoService
{
 // 注意: 若變更此處的介面名稱 "IGreetingService",也必須更新 App.config 中 "IGreetingService" 的參考。

    [ServiceContract]
    public interface IGreetingService
    {
        [OperationContract]
        string DoWork();
              
    }
}

Step 2:實作合約內容GreetingService.cs


namespace WcfDemoService
{
    // 注意: 若變更此處的類別名稱 "GreetingService",也必須更新 App.config 中 "GreetingService" 的參考。
    public class GreetingService : IGreetingService
    {
        public string DoWork()
        {
            return "This is return string2";
        }
      
    }
}
Step 3: 在主程式中撰寫開啟服務的程式碼
 class Program
 {
        static void Main(string[] args)
        {
            ServiceHost host = new ServiceHost(typeof(GreetingService));
            try
            {
                host.Open();
                Console.WriteLine("Server Opened !");
                Console.Read();
            }
            finally
            {
                if (host.State == CommunicationState.Faulted)
                    host.Abort();
                else
                    host.Close();
            }
        }
 }
Step 4: 建立App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.serviceModel>
        <behaviors>
            <serviceBehaviors>
                <behavior name="WcfDemoService.GreetingServiceBehavior">
                    <serviceMetadata httpGetEnabled="true" />
                    <serviceDebug includeExceptionDetailInFaults="false" />
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <services>
            <service behaviorConfiguration="WcfDemoService.GreetingServiceBehavior"
                name="WcfDemoService.GreetingService">
                <endpoint address="GreetingService" binding="basicHttpBinding" contract="WcfDemoService.IGreetingService" bindingConfiguration="basicHttpBindingConfiguration">
                    <identity>
                        <dns value="localhost" />
                    </identity>
                </endpoint>
                <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
                <host>
                    <baseAddresses>
                        <add baseAddress="http://192.168.0.103:8731"/>
                    </baseAddresses>
                </host>
            </service>
        </services>
      <bindings>
        <basicHttpBinding>
          <binding name="basicHttpBindingConfiguration" maxReceivedMessageSize="20971510">
            <readerQuotas maxStringContentLength="20971520" maxArrayLength="20971520"/>
         
          </binding>
        </basicHttpBinding>
      </bindings>
    </system.serviceModel>
</configuration>

Client端:
Step 1: 使用NetCFSvcUtil產生Proxy檔案,方法如下:
    a) 先執行host程式
    b)在cmd下cd到NetCFSvcUtil.exe的路徑下,輸入NetCFSvcUtil.exe http://host ip:host port/  按          下enter後會產生兩個檔案GreetingService.csCFClientBase.cs
        

Step 2:建立.net compact framework專案並匯入GreetingService.csCFClientBase.cs

Step 3: 在程式中撰寫呼叫wcf service的程式碼
private void btnGetStringByWCF_Click(object sender, EventArgs e)
{
System.ServiceModel.Channels.Binding binding = 
GreetingServiceClient.CreateDefaultBinding();
   string address = GreetingServiceClient.EndpointAddress.Uri.ToString();
   GreetingServiceClient m_proxy = 
new GreetingServiceClient(binding, new System.ServiceModel.EndpointAddress(address));
   
string GetString=m_proxy.DoWork();
  this.textBox1.Text = GetString;
}

2014年2月24日 星期一

[C#] 使用LinQ連接MS SQL Server發生error 26

當使用LinQ連接資料庫時發生Error 26時(如下圖)

此時請檢查Web,Config (App.Config) 檔案,並且確認Connection String為何,然後至 dbml的design.cs中找尋LinQ所使用的Connect string與Web.Config中相同
    1.) 確認.Config中設定了哪些DB連線及其名稱:

   2.)檢查dbml的design.cs中所使用的DB連線

    上圖LinQ所使用的connection string為ConnectionString3,在.Config中就必須有ConnectString3的設定且必須是可以連接到的DB

2014年1月8日 星期三

2013年9月10日 星期二

[Visual Studio] 加入WCF服務參考時產生錯誤"無法為服務參考xxx產生程式碼"或加入參考時"建置系統已經參考這個元件"


When you add Service Reference into Silverlight project, some time you get “failed to generate code for the service reference…” error.  Which means Visual Studio is failed to generate client code, and if see “ServiceReferences.ClientConfig” file it is empty. This is the common error most of the people get.

Step 1. In "Add Service Reference", Get in to "Advance"
 
 
 
Step 2. uncheck the “Reuse types in referenced assemblies” check box and click on Ok button.
 
Once you click on Ok button in Service Reference dialog box, the client code will be generated and you will not get any error. Now if you open “ServiceReferences.ClientConfig” file you can see the generated code.


2013年8月5日 星期一

[C#] asp.net加入Silverlight的WCF service (可用於連接MSSQL)

Silverlight連接 MS SQL必須透過WCF;

Step1:
首先必須在asp.net 網頁中加入WCF Service:


Step2:
撰寫合約內容:

Step3: 
於Silverlight中加入服務參考

Step4:
於Silverlight xaml.cs中使用WCF Service,需注意的是這邊的WCF服務必須使用非同步的方式呼叫(1.先定義服務完成的事件處理函式2.設計事件處理函式內容3.呼叫服務)

2012年12月27日 星期四

[網路] 使用net use指令連接網路硬碟

假設遠端目錄為\\1.1.1.100\Data\  登入之帳號/密碼為Administrator/Password
若愈在本機電腦新增一網路硬碟(Y:)  連接至遠端目錄,則可於命令提示字元中輸入以下指令:

net use Y:  \\1.1.1.100\Data  user:Administrator "Password"

可將此指令寫於批次檔中,如此可達到開機自動連線的目的

2012年11月27日 星期二

[MS SQL] 予許遠端連線 MS SQL server 之防火牆設定

若SQL Server Configuration Manager (組態管理員) 已開啟1433 port,但仍無法遠端連線,通常是因為被防火牆擋掉了,此時只須將sqlserver.exe加入防火牆例外清單即可。方法如下:


使用控制台中的 Windows 防火牆項目,將程式例外加入至防火牆

  1. 在 [控制台] 中,於 [Windows 防火牆] 項目的 [例外] 索引標籤上,按一下 [新增程式]
  2. 瀏覽至您想要通過防火牆的 SQL Server,例如 C:\Program Files\Microsoft SQL Server\MSSQL11.<instance_name>\MSSQL\Binn,選取 sqlservr.exe,然後按一下 [開啟]
  3. 按一下 [確定]。

2012年11月20日 星期二

[Visual Studio] Windows 8 安裝Visual Studio 2008

在Windows 8下要安裝Visual Studio 2008必須先安裝好NET Framework 3.5;安裝的方法有兩種:
1.使用提示視窗中的線上安裝;但此種方法因使用網路,故速度慢,此不另說明
2.另一方式是使用Windows 8光碟(印像檔)安裝
安裝方式如下:
a.首先按下Win+x 開啟"命令提示字元(管理員)"
b.輸入dism.exe /online /enable-feature /featurename:NetFX3 
      /Source:X:\sources\sxs

  X:為Windows 8光碟目錄

安裝畫面入下















跑完100%後,此時依照正常方式安裝Visual Studio 2008即可




2012年10月6日 星期六

[Visual Studio] Debugging mode無法逐步執行

問題描述:
當程式於debugging mode中無法逐步執行(F10 or F11),常常會執行幾步後就跳開debugging mode;此為Visual Studio 2008 SP1的bug

解決方法:安裝 hotfix KB957912

2012年9月21日 星期五

[MSSQL] 解決SQL server connect的問題:error: 40


在安裝並設定好 SQL server 2008 之後
連線至 SQL server 出現下列問題:
請依照下列方式開啟遠端連線:

1. 開啟【SQL server 組態管理員】
2. 檢查【SQL server 網路組態】設定中的【SQLSERVER 的通訊協定】
    預設狀態下【TCP/IP】是不被啟用的
     啟用【TCP/IP】狀態

4. 接下來開啟【TCP/IP】設定中的【內容(R)】→【IP位址】→【IP/All】進行下圖的設定
5. 設定完成後重新啟動 SQL server
設定完成,確認資料庫是否已經可以連線!

2012年9月5日 星期三

[網路]多網卡Routing table設定



顯示目前路由表
route print

只顯示172開頭的路由表
route print 172*

假設電腦使用 1.有線區域網路2.無線區域網路;
其中有線網路為公司內部網路,IP為172.*.*.*     Gateway為172.17.0.1
無線為連外之網路,其Gateway為192.168.33.1 
若要指定預設的連線皆使用無線區域網路,則只需要將default gateway設定為192.168.33.1
如此所有連線皆會透過無線網路連出去(註1);
但此時因為所有連線都透過無線網路來連線,所以無法存取公司內部網路。

若要存取內部網路時,可以於Routing table中加入路由路徑,方法如下: 
於command line輸入:
route add  172.0.0.0 mask 255.0.0.0 172.17.0.1
此命令表示對於所有172.*開頭的IP位址我們皆走172.17.0.1這個gateway來連線 

若只要設定某個IP位址(例如172.17.2.111)透過172.17.0.1這個gateway,則輸入:
route add 172.17.2.111 mask 255.255.255.255 172.17.0.1

若要刪除某個路由規則,則輸入:
route delete x.x.x.x  
其中x.x.x.x為目的IP
ex.在上段中我們將172.17.2.111這個目的IP指定走172.17.0.1此Gateway,如果要刪除這個路由規則,則可輸入route delete 172.17.2.111



註1.切換default gateway方法如下:
route change 0.0.0.0 mask 0.0.0.0 x.x.x.x -p  
x.x.x.x為gateway
(-p 持續保持這個路由設定在啟動的系統上)

註2. 若路由表被改爛了只要輸入以下指令便可重設路由表
netsh winsock reset

2012年8月10日 星期五

[C#] 常用進制轉換

1. 十進制轉二、八、十六進制:
  Convert.ToString(Dint, 2)   //Dint為十進制,第二個引數為欲轉成的進制

2. 二進制轉十進制
  Convert.ToInt32(str,2)  //str為二進制字串

2012年7月30日 星期一

[C#]設定系統時間


//設定格林威治時間
[DllImport("kernel32.dll")]
private extern static uint SetSystemTime(ref SYSTEMTIME lpSystemTime);

使用上面方式對於使用台北時間的系統而言看到的時間會是設定時間+8小時;
需改為下述方法設定時間才可正確顯示。


//系統設定時間
[DllImport("Kernel32.dll")]
public static extern bool SetLocalTime(ref SYSTEMTIME lpSystemTime);

其中
public struct SYSTEMTIME
        {
            public ushort wYear;
            public ushort wMonth;
            public ushort wDayOfWeek;
            public ushort wDay;
            public ushort wHour;
            public ushort wMinute;
            public ushort wSecond;
            public ushort wMilliseconds;
        }

函式呼叫方式如下:

SYSTEMTIME systime = new SYSTEMTIME();


                // Set config date and time
                systime.wYear = (ushort)(lYear);
                systime.wMonth = (ushort)(lMonth);
                systime.wDay = (ushort)(lDay);
                systime.wHour = (ushort)(lhour);
                systime.wMinute = (ushort)(lMini);
                systime.wSecond = (ushort)(lSec);
                systime.wDayOfWeek = (ushort)(lWeek);
                SetLocalTime(ref systime);

2012年4月20日 星期五

[XP]螢幕保護程式無法設定(皆反白)的解決方法


1.執行登錄編輯程式 Regedit.exe (開始->執行->輸入「regedit」按enter)
2.找到HKEY_CURRECT_USER\software\policies\microsoft\windows\control panel\desktop
3.然後遊標停在「desktop」把整個目錄都刪掉,大功告成!