2014年12月24日 星期三

Invoke() & beginInvoke() + EndInvoke()

//winform
//在不同執行續下想要呼叫前端物件時可以使用invoke()來切換當前執行續
control.invoke()
//使用invoke()是同步執行,執行完invoke()中程式內容後才會接著執行下面的程式
control.BeginInvoke()
//使用BeginInvoke()是非同步執行,兩邊程式都會一起執行
control.EndInvoke()
//在使用BeginInvoke()後,使用EndInvoke(),則程式會停在這裡,等待BeginInvoke()的內容執行完成
//wpf
control.Dispatcher.Invoke()
//其實跟winform差不多,就是多了Dispatcher
control.Dispatcher.BeginIvoke()
view raw invoke.cs hosted with ❤ by GitHub

2014年12月21日 星期日

WPF 設定動畫fps

如果常常在使用Animation的人,應該會發現你的程式cpu使用率異常的高,這是因為wpf內建設定動畫的fps是60 想要降低cpu使用率有兩個方法,第一個是把動畫做成gif直接嵌入,或是在程式初始化時把fps設定為30~40(一般人類肉眼可辨識的極限大概在30左右) 以下是設定fps的程式碼,寫在InitializeComponent()之前
//設定動畫fps
Timeline.DesiredFrameRateProperty.OverrideMetadata(
typeof(Timeline),
new FrameworkPropertyMetadata { DefaultValue = 30 }
);
view raw fps.cs hosted with ❤ by GitHub

2014年12月15日 星期一

產生qr_code圖片(base64)

最近專案上用到了QR CODE,這個class可以把字串轉成QR code圖片
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using ZXing;
using ZXing.QrCode;
/// <summary>
/// cs_Qrcode_Generate 的摘要描述
/// </summary>
public class cs_Qrcode_Generate
{
public cs_Qrcode_Generate()
{
//
// TODO: 在這裡新增建構函式邏輯
//
}
public string hashString(string s)
{
string result="";
return result;
}
public string Gen_Base64(String s){//字數不可超過300字
string sEncode = "utf-8"; //---或者gb2312
string EncoderContent = GetEncodingString(s,sEncode);
if (s.Length > 300) return null;
IBarcodeWriter writer = new BarcodeWriter
{
Format = BarcodeFormat.QR_CODE,
Options = new QrCodeEncodingOptions
{
Width = 400,
Height = 400
}
};
var result = writer.Write(EncoderContent);
var bitmap = new Bitmap(result);
return Convert.ToBase64String(ImageToByte2(bitmap));
}
//轉碼
private string GetEncodingString(string srcString, string sEncode)
{
Encoding e8859Encode = Encoding.GetEncoding("iso-8859-1");
Encoding srcEncode = Encoding.Unicode;
Encoding dstEncode = Encoding.GetEncoding(sEncode);
byte[] srcBytes = srcEncode.GetBytes(srcString);
byte[] dstBytes = Encoding.Convert(srcEncode, dstEncode, srcBytes);
char[] dstChars = new char[e8859Encode.GetCharCount(dstBytes, 0, dstBytes.Length)];
e8859Encode.GetChars(dstBytes, 0, dstBytes.Length, dstChars, 0);
return new string(dstChars);
}
//bitmap轉byte[] 記憶體
public static byte[] ImageToByte2(Image img)
{
byte[] byteArray = new byte[0];
using (MemoryStream stream = new MemoryStream())
{
img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
stream.Close();
byteArray = stream.ToArray();
}
return byteArray;
}
}
view raw qr_code.cs hosted with ❤ by GitHub

c#內建加解密

以前加解密都是自己來,左移,右移,AND,OR 最近發現c#內建不少加解密的函式,還蠻容易使用的,下面是從其他人blog抓來的code,有附連結
C# 使用 MD5, DES, RSA 演算法加解密
在 .NET Framework 中有個 namespace 是專門處理加解密動作 System.Security.Cryptography 針對許多種加解密方式都有對應的類別來處理 列出三種加密法實作 其它加密碼如 SHA1 系列與 MD5 語法相似,AES 與 DES 語法相似 就不另外寫出來了 PS. 以下部份資料取至 維基百科
MD5 演算法
MD5 即 Message-Digest Algorithm 5,是電腦廣泛使用的雜湊演算法之一 其演算法複雜度和不可逆性,通常用於確保資訊傳輸完整一致 因其不可逆性,所以只有加密的函式,沒有解密的函式
/// <summary>
/// 取得 MD5 編碼後的 Hex 字串
/// 加密後為 32 Bytes Hex String (16 Byte)
/// </summary>
/// <span name="original" class="mceItemParam"></span>原始字串</param>
/// <returns></returns>
public static string GetMD5(string original)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] b = md5.ComputeHash(Encoding.UTF8.GetBytes(original));
return BitConverter.ToString(b).Replace("-", string.Empty);
}
DES 加解密演算法
DES 加密法於 1977 年被聯邦政府列為數據加密標準 其加解密速度非常快速,但因為 56 位元金鑰過短 很有可能於 24 小時內被破解 如果需要安全一點的加密方式,可以考慮改用 AES 機制 AES 語法與 DES 大致相同,只在加解密的金鑰 KEY 及 IV 長度不同 加密及解碼需使用相同的金鑰
/// <summary>
/// DES 加密字串
/// </summary>
/// <span name="original" class="mceItemParam"></span>原始字串</param>
/// <span name="key" class="mceItemParam"></span>Key,長度必須為 8 個 ASCII 字元</param>
/// <span name="iv" class="mceItemParam"></span>IV,長度必須為 8 個 ASCII 字元</param>
/// <returns></returns>
public static string EncryptDES(string original, string key, string iv)
{
try
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
des.Key = Encoding.ASCII.GetBytes(key);
des.IV = Encoding.ASCII.GetBytes(iv);
byte[] s = Encoding.ASCII.GetBytes(original);
ICryptoTransform desencrypt = des.CreateEncryptor();
return BitConverter.ToString(desencrypt.TransformFinalBlock(s, 0, s.Length)).Replace("-", string.Empty);
}
catch { return original; }
}
/// <summary>
/// DES 解密字串
/// </summary>
/// <span name="hexString" class="mceItemParam"></span>加密後 Hex String</param>
/// <span name="key" class="mceItemParam"></span>Key,長度必須為 8 個 ASCII 字元</param>
/// <span name="iv" class="mceItemParam"></span>IV,長度必須為 8 個 ASCII 字元</param>
/// <returns></returns>
public static string DecryptDES(string hexString, string key, string iv)
{
try
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
des.Key = Encoding.ASCII.GetBytes(key);
des.IV = Encoding.ASCII.GetBytes(iv);
byte[] s = new byte[hexString.Length / 2];
int j = 0;
for (int i = 0; i < hexString.Length/2; i++)
{
s[i] = Byte.Parse(hexString[j].ToString() + hexString[j + 1].ToString(), System.Globalization.NumberStyles.HexNumber);
j += 2;
}
ICryptoTransform desencrypt = des.CreateDecryptor();
return Encoding.ASCII.GetString(desencrypt.TransformFinalBlock(s, 0, s.Length));
}
catch { return hexString; }
}
RSA 加解密演算法
RSA 是一種非對稱性加密演算法,其原理是以公鑰及私鑰來處理加解密 簡單來說,公鑰可以提供給任何需要加密的人,但是私鑰必須妥善保存 加密時以公鑰處理即可,但解密必須有私鑰
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
// 公鑰 xml 字串
publicXml = rsa.ToXmlString(false);
// 私鑰 xml 字串
privateXml = rsa.ToXmlString(true);
// 公鑰
publicParameter = rsa.ExportParameters(false);
// 私鑰
privateParameter = rsa.ExportParameters(true);
在 .NET Framework 中公私鑰可以 xml 及 RSAParameters 類別型態存在 而金鑰產生最簡單的方式是由 RSACryptoServiceProvider 類別來產生 每次初始化 RSACryptoServiceProvider 類別時即會亂數產生一組金鑰
加解密時只要使用同一組金鑰 (公私鑰) 即可
view plaincopy to clipboardprint?
/// <summary>
/// RSA 加密字串
/// </summary>
/// <span name="original" class="mceItemParam"></span>原始字串</param>
/// <span name="xmlString" class="mceItemParam"></span>公鑰 xml 字串</param>
/// <returns></returns>
public static string EncryptRSA(string original, string xmlString)
{
try
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(xmlString);
byte[] s = Encoding.ASCII.GetBytes(original);
return BitConverter.ToString(rsa.Encrypt(s, false)).Replace("-", string.Empty);
}
catch { return original; }
}
/// <summary>
/// RSA 加密字串
/// 加密後為 256 Bytes Hex String (128 Byte)
/// </summary>
/// <span name="original" class="mceItemParam"></span>原始字串</param>
/// <span name="parameters" class="mceItemParam"></span>公鑰 RSAParameters 類別</param>
/// <returns></returns>
public static string EncryptRSA(string original, RSAParameters parameters)
{
try
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(parameters);
byte[] s = Encoding.ASCII.GetBytes(original);
return BitConverter.ToString(rsa.Encrypt(s, false)).Replace("-", string.Empty);
}
catch { return original; }
}
/// <summary>
/// RSA 解密字串
/// </summary>
/// <span name="hexString" class="mceItemParam"></span>加密後 Hex String</param>
/// <span name="xmlString" class="mceItemParam"></span>私鑰 xml 字串</param>
/// <returns></returns>
public static string DecryptRSA(string hexString, string xmlString)
{
try
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(xmlString);
byte[] s = new byte[hexString.Length / 2];
int j = 0;
for (int i = 0; i < hexString.Length/2; i++)
{
s[i] = Byte.Parse(hexString[j].ToString() + hexString[j + 1].ToString(), System.Globalization.NumberStyles.HexNumber);
j += 2;
}
return Encoding.ASCII.GetString(rsa.Decrypt(s, false));
}
catch { return hexString; }
}
/// <summary>
/// RSA 解密字串
/// </summary>
/// <span name="hexString" class="mceItemParam"></span>加密後 Hex String</param>
/// <span name="parameters" class="mceItemParam"></span>私鑰 RSAParameters 類別</param>
/// <returns></returns>
public static string DecryptRSA(string hexString, RSAParameters parameters)
{
try
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(parameters);
byte[] s = new byte[hexString.Length / 2];
int j = 0;
for (int i = 0; i < hexString.Length/2; i++)
{
s[i] = Byte.Parse(hexString[j].ToString() + hexString[j + 1].ToString(), System.Globalization.NumberStyles.HexNumber);
j += 2;
}
return Encoding.ASCII.GetString(rsa.Decrypt(s, false));
}
catch { return hexString; }
}
原文 http://carllee413.pixnet.net/blog/post/3202781-c%23-%E4%BD%BF%E7%94%A8-md5,-des,-rsa-%E6%BC%94%E7%AE%97%E6%B3%95%E5%8A%A0%E8%A7%A3%E5%AF%86-

2014年12月11日 星期四

取得當前路徑

取得當前Server根目錄(server中叫用的cs文件) HttpContext.Current.Server.MapPath("/") 取得當前Server根目錄(aspx.cs) Server.MapPath("/")

2014年12月9日 星期二

定期執行function

10分鐘執行一次
Thread t = new Thread(() =>
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Elapsed += timer_Elapsed;
timer.Interval = 60000;
timer.Enabled = true;
//timer.Start();
});
t.IsBackground = true;
t.Start();
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
YourFunction();
}
view raw timer_task.cs hosted with ❤ by GitHub

2014年12月3日 星期三

java串流傳送接收

//socket 讀取字串
InputStream is = socket_reader.getInputStream();
//1.用string來接
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message;
//有時候會有多筆資料在buffer裡,必須判斷buffer是否已被讀取完
while((message = br.readLine()) != null) {
if( message != "") Process_RData_reader(message);
}
//2.用byte[]來接
byte[] buffer=new byte[4096];
BufferedInputStream bis= new BufferInputStream(is);
int length = 0;
while((length = bis.read(buffer)) != -1)
{
byte[] buffer_T = new byte[length];
for(int i=0;i<length;i++)
{
buffer_T[i] = buffer[i];
}
}
//讀取檔案
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream ois = new ObjectInputStream(fis);
_listTag = (Object)ois.readObject();
ois.close();
//寫入檔案
FileOutputStream fos = new FileOutputStream("data.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(Object);
oos.flush();
oos.close();

嘗試連線

//寫在webservice中用來確認對方是否斷線
string ip = Convert.ToString(context.Request["IP"]) ?? "";
Socket client=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
try{
Thread t = new Thread(() =>//使用Thread 當對方無回應時直接跳出線程
{
Thread.Sleep(1 * 1000);//等待1秒後
if (!client.Connected) //如果還沒連上
{
context.Response.Write("");//回應前端
client.Close();//關閉socket
}
Thread.CurrentThread.Abort();//中斷線程
});
t.Start();
client.Connect(IPAddress.Parse(ip), 80);//嘗試連線
context.Response.Write("ok");
}
catch (Exception ee)
{
context.Response.Write("failed");
client.Close();
return;
}
view raw ping.cs hosted with ❤ by GitHub

List,ObservableCollection,SortableObservableCollection

ObservableCollection就是實作了INotifyCollectionChanged的List INotifyCollectionChanged是當資料改變時,通知介面層的一個接口,在WPF與silverlight中被大量使用在資料繫結上 ObservableCollection與List之間可互相轉換
List<T> list = new List(o.ToList());
ObservableCollection o = new ObservableCollection(list);
SortableObservableCollection 可自動進行排列的ObservableCollection物件
//Sortable ObservableCollection
public class SortableObservableCollection<T> : ObservableCollection<T>
{
public SortableObservableCollection()
{
}
public SortableObservableCollection(List<T> list)
: base(list)
{
}
public SortableObservableCollection(IEnumerable<T> collection)
: base(collection)
{
}
public void Sort<TKey>(Func<T, TKey> keySelector, System.ComponentModel.ListSortDirection direction)
{
switch (direction)
{
case System.ComponentModel.ListSortDirection.Ascending:
{
ApplySort(Items.OrderBy(keySelector));
break;
}
case System.ComponentModel.ListSortDirection.Descending:
{
ApplySort(Items.OrderByDescending(keySelector));
break;
}
}
}
public void Sort<TKey>(Func<T, TKey> keySelector, IComparer<TKey> comparer)
{
ApplySort(Items.OrderBy(keySelector, comparer));
}
private void ApplySort(IEnumerable<T> sortedItems)
{
var sortedItemsList = sortedItems.ToList();
foreach (var item in sortedItemsList)
{
Move(IndexOf(item), sortedItemsList.IndexOf(item));
}
}
}

RichTextBox單行長度設定

有時候不希望RichTextBox一直換行,可以來修改單行長度 看似簡單,卻花了我一個多小時才找到,WPF的資料實在太少了
<!--PageWidth內填入單行最大長度(16進位)-->
<RichTextBox.Resources>
<Style TargetType="{x:Type Paragraph}">
<Setter Property="Margin" Value="0"/>
</Style>
</RichTextBox.Resources>
<RichTextBox.Document>
<FlowDocument PageWidth="2048"/><!--字元拉長到2048-->
</RichTextBox.Document>
view raw RichTextBox.xml hosted with ❤ by GitHub

型別轉換

幾個常用的轉換
//char陣列轉String
string str = new String(charArray);
//String轉Char[]
string str = "12345670000001";
char[] charArray = str.ToCharArray();
//string轉byte[]
byte[] byteArray = System.Text.Encoding.Default.GetBytes(str);
//byte轉string
string str = System.Text.Encoding.Default.GetString( byteArray );
//特殊轉換
//byte[] 轉成原16進制格式的string,例如0xae00cf, 轉換成 "ae00cf";new byte[]{ 0x30, 0x31}轉成"3031":
public static string ToHexString ( byte[] bytes ) // 0xae00cf => "AE00CF "
{
string hexString = string.Empty;
if ( bytes != null )
{
StringBuilder strB = new StringBuilder ();
for ( int i = 0; i < bytes.Length; i++ )
{
strB.Append ( bytes[i].ToString ( "X2" ) );
}
hexString = strB.ToString ();
}
return hexString;
}
//反過來,16進制格式的string 轉成byte[],例如, "ae00cf"轉換成0xae00cf,長度縮減一半;"3031" 轉成new byte[]{ 0x30, 0x31}:
public static byte[] GetBytes(string hexString, out int discarded)
{
discarded = 0;
string newString = "";
char c;
// remove all none A-F, 0-9, characters
for (int i=0; i<hexString.Length; i++)
{
c = hexString[i];
if (IsHexDigit(c))
newString += c;
else
discarded++;
}
// if odd number of characters, discard last character
if (newString.Length % 2 != 0)
{
discarded++;
newString = newString.Substring(0, newString.Length-1);
}
int byteLength = newString.Length / 2;
byte[] bytes = new byte[byteLength];
string hex;
int j = 0;
for (int i=0; i<bytes.Length; i++)
{
hex = new String(new Char[] {newString[j], newString[j+1]});
bytes[i] = HexToByte(hex);
j = j+2;
}
return bytes;
}
//出處 :http://www.cnblogs.com/Mainz/archive/2008/04/09/1144242.html
view raw convert.cs hosted with ❤ by GitHub
bitmap轉byte[]
//bitmap轉byte[] 記憶體
public static byte[] ImageToByte2(Image img)
{
byte[] byteArray = new byte[0];
using (MemoryStream stream = new MemoryStream())
{
img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
stream.Close();
byteArray = stream.ToArray();
}
return byteArray;
}
//bitmap轉byte[]
public static byte[] ImageToByte(Image img)
{
ImageConverter converter = new ImageConverter();
return (byte[])converter.ConvertTo(img, typeof(byte[]));
}
view raw bitmaptobyte.cs hosted with ❤ by GitHub
C# 常用功能-最小化程式至系統列


//寫在form.cs底下
//工具箱加入NotifyIcon
//控制項大小改變時觸發
//form的resize事件
private void Form1_Resize(object sender, EventArgs e)
{
if (FormWindowState.Minimized == WindowState)
{
this.ShowInTaskbar = false;
notifyIcon1.Visible = true;
Hide();
}
if (FormWindowState.Maximized == WindowState)
{
this.ShowInTaskbar = true;
notifyIcon1.Visible = false;
Show();
}
}
//雙擊工作列小圖示
//NotifyIcon的雙擊事件
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
WindowState = FormWindowState.Normal;
notifyIcon1.Visible = false;
this.ShowInTaskbar = true;
Show();
}
view raw minimize.cs hosted with ❤ by GitHub