接著要安裝開發程式所需要的 library:
Ubuntu 8.04 => libmysqlclient15-dev
相關的 header 檔案都會放在 /usr/include/ 裡面,而實際運作的函式庫則會存在 /usr/lib/mysql 中
若是撰寫 mysql 相關程式時,編譯方式如下:
gcc <程式名稱> -I /usr/include/mysql -L /usr/lib/mysql -l mysqlclient -o <輸出檔案名稱>
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.ComponentModel;
namespace SocketConn
{
class SocketServer
{
#region private property
/// /// socket server TCP port number
/// private int _PortNumber;
/// /// TCP Listener
/// private TcpListener _Listener;
/// /// 用來處理 Listener 工作的執行緒
/// private BackgroundWorker _bgwServer = new BackgroundWorker();
/// /// socker client 識別編號
/// private int _ClientNo = 0;
#endregion
#region static public property
/// /// 工作進行中產生之訊息
/// public static List sMessages = new List();
#endregion
#region constructor
/// /// constructor
/// ///
socket server TCP port number
public SocketServer(int inPortNumber)
{
this._PortNumber = inPortNumber;
//委派事件
_bgwServer.DoWork += new DoWorkEventHandler(_bgwServer_DoWork);
}
#endregion
#region public method
/// /// 開始監聽
/// public void Start()
{
if (!_bgwServer.IsBusy)
_bgwServer.RunWorkerAsync();
}
#endregion
#region BackgroundWorker
///
/// 處理 Listener 工作
/// ///
///
private void _bgwServer_DoWork(object sender, DoWorkEventArgs e)
{
try
{
//若 TCP Listner 正在工作,則停止
if (_Listener != null)
_Listener.Stop();
//初始化 TCPListener
_Listener = new TcpListener(IPAddress.Any, _PortNumber);
//啟動 listener
_Listener.Start();
sMessages.Add(" >> " + "Server Started");
//========== 持續接受監聽 socket client 的連線 ========== (start)
while (true)
{
//監聽到來自 socket client 的連線要求
TcpClient socket4Client = _Listener.AcceptTcpClient();
//累加 socket client 識別編號
_ClientNo++;
sMessages.Add(" >> " + "Client Request No:" + Convert.ToString(_ClientNo) + " started!");
//產生 BackgroundWorker 負責處理每一個 Socket Client 的要求
ClientRequestHandler handler = new ClientRequestHandler(_ClientNo, socket4Client);
handler.DoCommunicate();
}
//========== 持續接受監聽 socket client 的連線 ========== (end)
}
catch (Exception exp)
{
sMessages.Add(exp.ToString());
}
}
#endregion
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.ComponentModel;
namespace SocketConn
{
class ClientRequestHandler
{
#region private property
/// /// socket client 識別號碼
/// private int _ClientNo;
/// /// socket client reuqest
/// private TcpClient _TcpClient;
#endregion
#region constructor
/// /// constructor
/// ///
socket client 識別號碼
///
socket client reuqest
public ClientRequestHandler(int inClientNo, TcpClient inTcpClient)
{
this._ClientNo = inClientNo;
this._TcpClient = inTcpClient;
}
#endregion
#region public method
/// /// server & client 間相互進行通訊
/// public void DoCommunicate()
{
//產生 BackgroundWorker 負責處理每一個 socket client 的 reuqest
BackgroundWorker bgwSocket = new BackgroundWorker();
bgwSocket.DoWork += new DoWorkEventHandler(bgwSocket_DoWork);
bgwSocket.RunWorkerAsync();
}
#endregion
#region BackgroundWorker
/// /// 處理 socket client request
/// private void bgwSocket_DoWork(object sender, DoWorkEventArgs e)
{
//server & client 已經連線完成
while (_TcpClient.Connected)
{
//取得網路串流物件,取得來自 socket client 的訊息
NetworkStream netStream = _TcpClient.GetStream();
byte[] readBuffer = new byte[1024];
int count = 0;
if ((count = netStream.Read(readBuffer, 0, readBuffer.Length)) != 0)
{
string clientRequest = Encoding.UTF8.GetString(readBuffer, 0, count);
SocketServer.sMessages.Add(" >> " + "From client(" + _ClientNo + ") =>" + clientRequest);
//正確取得 client requst,再回傳給 client
string serverResponse = "Server to clinet(" + _ClientNo + ") => message: " + clientRequest;
byte[] sendBytes = Encoding.UTF8.GetBytes(serverResponse);
netStream.Write(sendBytes, 0, sendBytes.Length);
netStream.Flush();
SocketServer.sMessages.Add(" >> " + serverResponse);
}
}
}
#endregion
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace SocketConn
{
class SocketClient
{
#region private property
/// /// 遠端 socket server IP 位址
/// private string _RemoteIpAddress;
/// /// 遠端 socket server 所監聽的 port number
/// private int _RemotePortNumber;
/// /// socket client 物件(連接遠端 socket server 用)
/// private TcpClient _TcpClient;
#endregion
#region public static property
public static List sMessages = new List();
#endregion
#region constructor
/// /// constructor
/// ///
遠端 socket server IP 位址
///
遠端 socket server 所監聽的 port number
public SocketClient(string inRemoteIpAddr, int inRemotePortNum)
{
this._RemoteIpAddress = inRemoteIpAddr;
this._RemotePortNumber = inRemotePortNum;
}
#endregion
#region public method
/// /// 連線至 socket server
/// public void Connect()
{
//初始化 socket client
_TcpClient = new TcpClient();
_TcpClient.Connect(_RemoteIpAddress, _RemotePortNumber);
sMessages.Add("Client Socket Program - Server Connected ...");
}
/// /// 傳送訊息至 socker server
/// ///
訊息
/// socker server 回傳結果
public string Send(string inMessage)
{
try
{
//取得用來傳送訊息至 socket server 的 stream 物件
NetworkStream serverStream = _TcpClient.GetStream();
//將資料轉為 byte[]
byte[] outStream = System.Text.Encoding.UTF8.GetBytes(inMessage);
//將資料寫入 stream object (表示傳送資料至 socket server)
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
//讀取 socket server 回傳值並轉為 string
byte[] inStream = new byte[10025];
serverStream.Read(inStream, 0, (int)_TcpClient.ReceiveBufferSize);
string returndata = System.Text.Encoding.UTF8.GetString(inStream);
sMessages.Add("Data from Server : " + returndata);
return returndata;
}
catch (Exception exp)
{
sMessages.Add(exp.ToString());
return exp.ToString();
}
}
#endregion
}
}
public string test { get; set; }大概就以上這些語法.......
var myVar = "text";
var newObject = new MyObject { Name = "myobject", Age = 12; }
'xxxxxxx' 不是標記成 abstract 或 extern,因此必須宣告主體上面就是因為用了第一段程式碼的第一行語法所出現的錯誤.....(但這是 2.0 才會出現的...)
using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
//定義各種不同型態的資料
Object[] array = { "String", 12, true, 'a' };
var types = array.Select(item => item.GetType().Name) //選取集合中資料的型態
.OrderBy(type => type); //根據型態進行排序
/* 執行結果:
Boolean
Char
Int32
String */
ObjectDumper.Write(types);
Console.ReadLine();
}
}
using System;
using System.Linq;
using LinqInAction.LinqBooks.Common;
class Program
{
static void Main(string[] args)
{
Book[] books = { new Book { Title = "LINQ In Action" },
new Book { Title = "LINQ For Fun" },
new Book { Title = "Extreme LINQ" } };
var titles = books.Where(book => book.Title.Contains("Action")) //取得 Title 欄位包含 "Action" 關鍵字的書籍資料
.Select(book => book.Title); //取得 Title 欄位
/* 執行結果:
LINQ In Action */
ObjectDumper.Write(titles);
Console.ReadLine();
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using LinqInAction.LinqBooks.Common;
class Program
{
static void Main(string[] args)
{
//即使資料換成是 List,LINQ 的語法也是相同的!
Listbooks = new List () { new Book { Title = "LINQ In Action" },
new Book { Title = "LINQ For Fun" },
new Book { Title = "Extreme LINQ" } };
var titles = books.Where(book => book.Title.Contains("Action")) //取得 Title 欄位包含 "Action" 關鍵字的書籍資料
.Select(book => book.Title); //取得 Title 欄位
/* 執行結果:
LINQ In Action */
ObjectDumper.Write(titles);
Console.ReadLine();
}
}
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
DictionarymyNumbers = new Dictionary ();
myNumbers.Add(0, "zero");
myNumbers.Add(1, "One");
myNumbers.Add(2, "Two");
myNumbers.Add(3, "Three");
myNumbers.Add(4, "Four");
//透過 query operator 的方式取得偶數值
var evenNumbers01 = myNumbers.Where(number => number.Key % 2 == 0)
.Select(number => number.Value);
ObjectDumper.Write(evenNumbers01);
//也可以透過 query expression 的方式取得偶數值
var evenNumbers02 = from number in myNumbers
where (number.Key % 2) == 0
select number.Value;
ObjectDumper.Write(evenNumbers02);
/*
以上兩個執行結果都會是:
Zero
Two
Four
*/
Console.ReadLine();
}
}
using System;
using System.Linq;
namespace DeferredQueryExecution
{
class Program
{
static double Square(double n)
{
//每呼叫 Square 就會印出下列訊息
Console.WriteLine("Computing Square(" + n + ")....");
return Math.Pow(n, 2);
}
static void Main(string[] args)
{
int[] numbers = { 1, 2, 3 };
//取得 numbers 陣列中所有元素的平方值並存入 query 集合物件中
var query =
from n in numbers
select Square(n);
//印出 query 集合物件的內容
foreach (var n in query)
Console.WriteLine(n);
Console.ReadLine();
}
}
}
Computing Square(1)....
Computing Square(2)....
Computing Square(3)....
1
4
9
Computing Square(1)....
1
Computing Square(2)....
4
Computing Square(3)....
9
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace CompleteCode
{
//為了將 Extension Method 定義在此類別, 要加上 static 關鍵字
//否則就要另外定義一個 static class 來放 Extension Method
static class Program
{
static void Main(string[] args)
{
//在呼叫時指定比對用的 function (使用 Lambda Expression)
DisplayProcesses(process => process.WorkingSet64 >= 20 * 1024 * 1024);
Console.ReadLine();
}
//定義 inner class
class ProcessData
{
public Int32 Id { get; set; }
public Int64 Memory { get; set; }
public string Name { get; set; }
}
//此處以委派(delegate)的方式將 match 函式交由呼叫端決定
//傳入的參數型態為 System.Diagnostics.Process
//回傳型態為 Boolean
static void DisplayProcesses(Funcmatch)
{
//此處變數型態會由 compiler 在編譯時決定
var processes = new List();
foreach (var process in Process.GetProcesses())
{
//使用 Object Initializer 的方式宣告物件並給定值
if (match(process))
processes.Add(new ProcessData { Id = process.Id, Name = process.ProcessName, Memory = process.WorkingSet64 });
}
Console.WriteLine("Total memory: {0} MB", processes.TotalMemory() / 1024 / 1024);
//透過 .NET 內建的 Extension Method,取得耗用記憶體最大的兩個 process 所耗費的記憶體總計
var top2Memory = processes.OrderByDescending(process => process.Memory)
.Take(2)
.Sum(process => process.Memory) / 1024 / 1024;
Console.WriteLine("Memory consumed by the two most processes: {0} MB", top2Memory);
//使用 Anonymous Type 宣告物件並顯示
var results = new { TotalMomery = processes.TotalMemory() / 1024 / 1024,
Top2Memory = top2Memory,
Processes = processes };
ObjectDumper.Write(results, 1);
}
//定義 Extension Method(計算記憶體總使用量)
//針對 IEnumerable型別進行擴充
static Int64 TotalMemory(this IEnumerableprocesses)
{
Int64 result = 0;
foreach (var process in processes)
result += process.Memory;
return result;
}
}
}
using System;
using System.Linq;
namespace HelloLinq
{
class Program
{
static void Main(string[] args)
{
//string array
string[] words = { "hello", "wonderful", "linq", "beautiful", "world" };
//取得陣列中字串長度小於等於 5 的字串
var shortwords = from word in words
where word.Length <= 5
select word;
/* hello
linq
world */
foreach (var word in shortwords)
Console.WriteLine(word);
//依照字串長度分群組
var groups = from word in words
orderby word ascending
group word by word.Length into lengthGroups
orderby lengthGroups.Key descending
select new { Length = lengthGroups.Key, Words = lengthGroups };
/*
words of length 9
beautiful
wonderful
words of length 5
hello
world
words of length 4
linq
*/
foreach (var group in groups)
{
Console.WriteLine("words of length " + group.Length);
foreach (string word in group.Words)
Console.WriteLine(" " + word);
}
Console.ReadLine();
}
}
}
using System;
using System.Linq;
using System.Xml.Linq;
namespace HelloLinqToXml
{
class Book
{
public string Publisher;
public string Title;
public int Year;
public Book(string title, string publisher, int year)
{
Title = title;
Publisher = publisher;
Year = year;
}
}
class Program
{
static void Main(string[] args)
{
//定義 object collection
Book[] books = new Book[] {
new Book("Ajax in Action", "Manning", 2005),
new Book("Windows Forms in Action", "Manning", 2006),
new Book("RSS and Atom in Action", "Manning", 2006)
};
//從 object collection 中取得資料後,並搭配 XML API 產生 XML 文件
XElement xml = new XElement("books",
from book in books
where book.Year == 2006
select new XElement("book",
new XAttribute("title", book.Title),
new XElement("publisher", book.Publisher)));
Console.WriteLine(xml);
Console.ReadLine();
}
}
}
using System;
using System.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data.SqlClient;
namespace HelloLinqToSql
{
class Program
{
static void Main(string[] args)
{
//設定資料來源
DataContext db = new DataContext(new SqlConnection("Server=CIC-GODLEON\\SQLEXPRESS;Database=northwind;Trusted_Connection=True;"));
//透過 LINQ 來取得資料
var contacts =
from contact in db.GetTable()
where contact.City == "Paris"
select contact;
foreach (var contact in contacts)
Console.WriteLine("Bonjour " + contact.Name);
Console.ReadLine();
}
}
///
/// 必須透過設定 attribute 的方式指定 class 和 DB table 的 mapping
/// 此處指定對應到 Customers 資料表
///
[Table(Name="Customers")]
class Contact
{
///
/// 同樣內部的設定也必須要透過 attribute 的方式設定 mapping
///
//未指定則對應到同名(CustomerID)欄位
[Column(IsPrimaryKey=true)]
public string CustomerID { get; set; }
//指定對應到 ContactName 欄位
[Column(Name="ContactName")]
public string Name { get; set; }
//對應 City 欄位
[Column]
public string City { get; set; }
}
}