2012年8月31日 星期五

C# double 無條件捨去

C# 中,關於 double 所有的函式及轉換成字串的方式,皆預設為四捨五入,對想要無條件捨去的是一大困擾。 若要實現無條件捨去,便只能用字串的方式來處理才行。
/// 
/// 無條件捨去
/// 
/// double value
/// 小數點後幾位
/// 
private string RoundDown(double d, int digits)
{
    if (d == Double.NaN || d == 0)
        return "0";

    string s = "";
    if (d.ToString().IndexOf(".") != -1)
    {
        if (digits == 0)
            s = d.ToString().Substring(0, d.ToString().IndexOf("."));
        else
        {
            int length = digits + d.ToString().IndexOf(".") + 1;
            if (d.ToString().Length < length)
                s = d.ToString().PadRight(length, '0');
            else
                s = d.ToString().Substring(0, digits + d.ToString().IndexOf(".") + 1);
        }
    }
    else
        return d.ToString();
    return s;
}

2010年11月1日 星期一

C# Handle Windows Event (Send and Receive)

Using C# to handle windows event, we have to declare some extern methods first.

[DllImport("Kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr OpenEvent(UInt32 dwDesiredAccess,
bool bInheritHandle, String lpName);

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr CreateEvent(IntPtr lpEventAttributes,
bool bManualReset, bool bInitialState, string lpName);

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CloseHandle(IntPtr hObject);

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool SetEvent(IntPtr hEvent);

For Sending event, use "CreateEvent", "SetEvent" and "CloseHandle".
For Receiving event, use "OpenEvent".

  • Send Event


  • // You could put CreateEvent in the contructor
    IntPtr evtHandle = CreateEvent(IntPtr.Zero, false, false, "CUSTOM_EVENT_NAME");

    // Each time you need to send the event, just call SetEvent.
    SetEvent(evtHandle);

    // Put this in the de-constructor(~Constructor) to close this handle.
    CloseHandle(evtHandle);

  • Receive Event


  • IntPtr evt;
    while (true)
    {
    if (OpenEvent(out evt))
    {
    AutoResetEvent arEvt = new AutoResetEvent(false);
    arEvt.SafeWaitHandle = new Microsoft.Win32.SafeHandles.SafeWaitHandle(evt, true);
    WaitHandle[] waitHandles = new WaitHandle[] { arEvt };
    while (true)
    {
    int waitResult = WaitHandle.WaitAny(waitHandles, 500, false);
    if (waitResult == 0)
    {
    //Do something
    }
    }
    }
    Thread.Sleep(2000);
    }


    private static bool OpenEvent(out IntPtr evt)
    {
    uint unEventPermissions = 2031619;
    // Same as EVENT_ALL_ACCESS value in the Win32 realm
    evt = OpenEvent(unEventPermissions, false, "CUSTOM_EVENT_NAME");
    if (evt == IntPtr.Zero)
    return false;
    else
    return true;
    }

2010年6月3日 星期四

C# 如何在Arraylis裡找出相同的值並計算出現次數

有一個 Arraylist 裡面有值為 {1,2,3,4,5,3,10,1,2,4,12,9,4} 等數字
要一個數字只顯示一次,不重複
並計算出每個數字共出現幾次?

顯示gridview 如下

Num Count
------------
1 2
2 2
3 2
4 3
5 1
9 1
10 1
12 1


public static void Main(string[] args)
{
int[] iArr = new int[] { 1, 2, 3, 4, 5, 3, 10, 1, 2, 4, 12, 9, 4 };

SortedDictionary<int, int> sDict = new SortedDictionary<int, int>();

foreach (int i in iArr)
{
if (sDict.ContainsKey(i))
{
int value = sDict[i];
sDict.Remove(i);
sDict.Add(i, value + 1);
}
else
sDict.Add(i, 1);
}

Console.WriteLine(" Num Count");
Console.WriteLine(" -------------- ");
foreach (KeyValuePair<int, int> kvp in sDict)
Console.WriteLine("{0,4}{0,8}", kvp.Key, kvp.Value);

Console.ReadKey();
}


Result:
CSharp_Array

2010年6月2日 星期三

C# : Simple Console Calendar


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace ConsoleCalendar
{
public class Program
{
public static void Main(string[] args)
{
int year, month, day;
Console.Write("請輸入年份:");
year = Convert.ToInt32(Console.ReadLine());
Console.Write("請輸入月份:");
month = Convert.ToInt32(Console.ReadLine());
Console.Write("請輸入日期:");
day = Convert.ToInt32(Console.ReadLine());

Console.Clear();
DateTime d = new DateTime(year, month, day);
Console.WriteLine("{0}/{1}/{2} {3} {4}", d.Year, d.Month, d.Day, d.DayOfWeek, DateTime.DaysInMonth(d.Year, d.Month));
PrintLine();
PrintRows(3, new string[] { "日", "一", "二", "三", "四", "五", "六" }, 7);
PrintLine();
PrintRows(4, GetDaysArray(d), 7);
PrintLine();
Console.ReadKey();
}

private static string[] GetDaysArray(DateTime dt)
{
List<string> list = new List<string>();

//Fill the spaces of first line
DateTime firstDay = new DateTime(dt.Year, dt.Month, 1);
switch (firstDay.DayOfWeek)
{
case DayOfWeek.Monday:
list.Add("");
break;
case DayOfWeek.Tuesday:
list.AddRange(new string[] { "", "" });
break;
case DayOfWeek.Wednesday:
list.AddRange(new string[] { "", "", "" });
break;
case DayOfWeek.Thursday:
list.AddRange(new string[] { "", "", "", "" });
break;
case DayOfWeek.Friday:
list.AddRange(new string[] { "", "", "", "", "" });
break;
case DayOfWeek.Saturday:
list.AddRange(new string[] { "", "", "", "", "", "" });
break;
}
//the date, 1 ~ 28 or 29 or 30 or 31
//mark the date for special color
for (int i = 1; i <= DateTime.DaysInMonth(dt.Year, dt.Month); i++)
{
if (i == dt.Day)
list.Add("{" + i + "}");
else
list.Add(i + "");
}
return list.ToArray();
}

private static void PrintLine()
{
Console.WriteLine(new string('-', 36));
}

private static void PrintRows(int width, string[] columns, int itemsPerLine)
{
StringBuilder sb = new StringBuilder();
int totalLines = columns.Length % itemsPerLine == 0 ? columns.Length / itemsPerLine : columns.Length / itemsPerLine + 1;
for (int i = 0; i < totalLines; i++)
{
for (int j = 0; j < itemsPerLine; j++)
{
int pos = i * itemsPerLine + j;
if (pos >= columns.Length)
break;
sb.Append("|" + AlignCentre(columns[pos], width));
}
sb.Append("|");
sb.Append("\n");
}

//Start to print
uint STD_OUTPUT_HANDLE = 0xfffffff5;
IntPtr hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
foreach (char c in sb.ToString().ToCharArray())
{
if (c == '{')
{
//SetConsoleTextAttribute(hConsole, 12);
Console.ForegroundColor = ConsoleColor.Red;
Console.Write(' ');
continue;
}
if (c == '}')
{
//SetConsoleTextAttribute(hConsole, 7);
Console.ForegroundColor = ConsoleColor.Gray;
Console.Write(' ');
continue;
}
Console.Write(c);
}
}

private static string AlignCentre(string text, int width)
{
if (string.IsNullOrEmpty(text))
return new string(' ', width);
else
return text.PadLeft(width - (width - text.Length) / 2).PadRight(width);
}

[DllImport("kernel32.dll")]
private static extern bool SetConsoleTextAttribute(IntPtr hConsoleOutput, int wAttributes);

[DllImport("kernel32.dll")]
private static extern IntPtr GetStdHandle(uint nStdHandle);

}
}



Result:
C#_Console_Calendar_A

C#_Console_Calendar_B

Source Code: Download

2010年3月29日 星期一

20100327 GARMIN 北宜之旅

中途休息站,坪林陳德利茶莊,我與 Partner
陳德利茶莊

北宜公路最高點
北宜最高點
北宜最高點

鳥瞰蘭陽平原
眺望蘭陽平原

礁溪火車站月台
礁溪火車站月台

兩鐵專車
兩鐵專車

2010年3月25日 星期四

MusicCopy

中文版

April 6, 2010 MusicCopy 0.6.1 Released Download

This is bug-fix release.
Fixed:
  • Prefix error
  • Parse mp3 tag information error


April 2, 2010 MusicCopy 0.6 Released Download

New function:

  • About
  • Display the version of the program and the release date.

  • Move & Sort
  • You coulld select one or many MP3s and then click the move button. It will change the sequece of the list. "Sort" function enabled when the files contain ID3v1 tag information. It is based on the same album and then sort by the track.

  • Display
  • It will display "Performer-Title" based on ID3v1 tag. If the file didn't have ID3v1 tag, show the filename instead.





"MusicCopy" is a small software to copy music files(MP3, WMA) from computer to the USB device.

OS: Windows XP Above (Tested on WinXP, Vista 32 bit, Win7 64 bit)
Library: .Net Framework 3.5 SP1 (Download) Note! Install this before excute.
Program: Download from here. Extract and double-click MusicCopy.exe



  • Tool Bar


    • Copy



      1. Target Folder
      2. Type the folder name in the text field, or click the folder icon to select. If the folder is not existed, it will create automatically. Note, if you choose the folder which is not under the removable device, it will raise an exception.
      3. Option
      4. The 3rd option will keep the sequence of song list.
      5. Start and Stop
      6. Click "Start" button to start, and then "Stop" button appeared.

    • Device List


      1. This window will display all removable devices in this computer. You could see the basic information of the device, including the drive label, size, available size and the file system. Select the target device which to be copied.

    • About


      1. Introduce the purpose of this software.


  • Header Information

  • Display the selected device.

  • Song List
  • Display the whole songs. You could add songs through the command bar or drag-and-drop from your folders or files. If you add from a folder, it will add all *.mp3 and *.wma files in this folder and sub-folders.

  • Command Bar

  • Add single file, add a folder and delete files.


  • Status

  • Display the total size in the song list and the free space of the target device. If the size of song list is bigger than device size, the color will convert to red.

2010年3月22日 星期一

汐止 ←→ 冷水坑 (小 3P)

去程:汐止國泰醫院→汐萬路→五指山涼亭→風櫃嘴→楓林橋→至善路→至善路71巷平菁街菁山路菁山路101巷→冷水坑遊客服務站

回程:冷水坑遊客服務站→菁山路101巷→菁山路→平菁街→至善路71巷→至善路→楓林橋→風櫃嘴→五指山涼亭→汐萬路→汐止國泰醫院

總里程:78.41KM
總騎乘時間:5:48:39

行程圖片