2014年7月28日 星期一

vbnet QRCode (使用:quricol32.dll )

參考來源1:QR CODE 二維條碼的簡介與列印 
參考來源2:Quricol - QR code generator library
參考來源3:This is a sample for create a QR Code using the library Quricol - QR code generator library 
--

  

vbnet 製作 Code 39

參考引用來源:[VB.NET] 生成 Code39 码 
--


一,新建 Code39.ashx 文档,代码如下:

Imports System.Web
Imports System.Web.Services
Imports System.Drawing
Imports System.IO

Public Class code39
    Implements System.Web.IHttpHandler

    Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest

        Dim sCode As String = String.Empty
        '清除該頁輸出緩存,設置該頁無緩存  
        context.Response.Buffer = True
        context.Response.ExpiresAbsolute = System.DateTime.Now.AddMilliseconds(0)
        context.Response.Expires = 0
        context.Response.CacheControl = "no-cache"
        context.Response.AppendHeader("Pragma", "No-Cache")
        '將Code39條碼寫入記憶體流,並將其以 "image/Png" 格式輸出  
        Dim oStream As MemoryStream = New MemoryStream()
        Try
            Dim oBmp As Bitmap = GetCode39(context.Request.QueryString("id"))
            oBmp.Save(oStream, System.Drawing.Imaging.ImageFormat.Png)
            oBmp.Dispose()
            context.Response.ClearContent()
            context.Response.ContentType = "image/Png"
            context.Response.BinaryWrite(oStream.ToArray())
        Finally
            '釋放資源  
            oStream.Dispose()
        End Try

    End Sub

    ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

    Private Function GetCode39(ByVal strSource As String) As Bitmap
        Dim x As Integer = 5
        '左邊界
        Dim y As Integer = 0
        '上邊界
        Dim WidLength As Integer = 2
        '粗BarCode長度
        Dim NarrowLength As Integer = 1
        '細BarCode長度
        Dim BarCodeHeight As Integer = 20
        'BarCode高度
        Dim intSourceLength As Integer = strSource.Length
        Dim strEncode As String = "010010100"
        '編碼字串 初值為 起始符號 *
        Dim AlphaBet As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%*"
        'Code39的字母
        'Code39的各字母對應碼
        Dim Code39 As String() = {"000110100", "100100001", "001100001", "101100000", "000110001", "100110000", _
         "001110000", "000100101", "100100100", "001100100", "100001001", "001001001", _
         "101001000", "000011001", "100011000", "001011000", "000001101", "100001100", _
         "001001100", "000011100", "100000011", "001000011", "101000010", "000010011", _
         "100010010", "001010010", "000000111", "100000110", "001000110", "000010110", _
         "110000001", "011000001", "111000000", "010010001", "110010000", "011010000", _
         "010000101", "110000100", "011000100", "010101000", "010100010", "010001010", _
         "000101010", "010010100"}
        strSource = strSource.ToUpper()
        '實作圖片
        Dim objBitmap As New Bitmap(((WidLength * 3 + NarrowLength * 7) * (intSourceLength + 2)) + (x * 2), BarCodeHeight + (y * 2))
        Dim objGraphics As Graphics = Graphics.FromImage(objBitmap)
        '宣告GDI+繪圖介面
        '填上底色
        objGraphics.FillRectangle(Brushes.White, 0, 0, objBitmap.Width, objBitmap.Height)

        Dim i As Integer = 0
        While i < intSourceLength
            '檢查是否有非法字元
            If AlphaBet.IndexOf(strSource(i)) = -1 OrElse strSource(i) = "*"c Then
                objGraphics.DrawString("含有非法字元", SystemFonts.DefaultFont, Brushes.Red, x, y)
                Return objBitmap
            End If
            '查表編碼
            strEncode = String.Format("{0}0{1}", strEncode, Code39(AlphaBet.IndexOf(strSource(i))))
            System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1)
        End While

        strEncode = String.Format("{0}0010010100", strEncode)
        '補上結束符號 *
        Dim intEncodeLength As Integer = strEncode.Length
        '編碼後長度
        Dim intBarWidth As Integer

        Dim ii As Integer = 0
        While ii < intEncodeLength
            '依碼畫出Code39 BarCode
            intBarWidth = If(strEncode(ii) = "1"c, WidLength, NarrowLength)
            objGraphics.FillRectangle(If(ii Mod 2 = 0, Brushes.Black, Brushes.White), x, y, intBarWidth, BarCodeHeight)
            x += intBarWidth
            System.Math.Max(System.Threading.Interlocked.Increment(ii), ii - 1)
        End While
        Return objBitmap
    End Function

End Class

純 C# 產生Code39 BarCode 圖片

參考引用來源:純 C# 產生Code39 BarCode 圖片
--
using System.Drawing;
using System.Drawing.Imaging;
private Bitmap GetCode39(string strSource)
{
  int x = 5; //左邊界
  int y = 0; //上邊界
  int WidLength = 2; //粗BarCode長度
  int NarrowLength = 1; //細BarCode長度
  int BarCodeHeight = 24; //BarCode高度
  int intSourceLength = strSource.Length;
  string strEncode = "010010100"; //編碼字串 初值為 起始符號 *

  string AlphaBet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%*"; //Code39的字母

  string[] Code39 = //Code39的各字母對應碼
  {
       /* 0 */ "000110100",
       /* 1 */ "100100001",
       /* 2 */ "001100001",
       /* 3 */ "101100000",
       /* 4 */ "000110001",
       /* 5 */ "100110000",
       /* 6 */ "001110000",
       /* 7 */ "000100101",
       /* 8 */ "100100100",
       /* 9 */ "001100100",
       /* A */ "100001001",
       /* B */ "001001001",
       /* C */ "101001000",
       /* D */ "000011001",
       /* E */ "100011000",
       /* F */ "001011000",
       /* G */ "000001101",
       /* H */ "100001100",
       /* I */ "001001100",
       /* J */ "000011100",
       /* K */ "100000011",
       /* L */ "001000011",
       /* M */ "101000010",
       /* N */ "000010011",
       /* O */ "100010010",
       /* P */ "001010010",
       /* Q */ "000000111",
       /* R */ "100000110",
       /* S */ "001000110",
       /* T */ "000010110",
       /* U */ "110000001",
       /* V */ "011000001",
       /* W */ "111000000",
       /* X */ "010010001",
       /* Y */ "110010000",
       /* Z */ "011010000",
       /* - */ "010000101",
       /* . */ "110000100",
       /*' '*/ "011000100",
       /* $ */ "010101000",
       /* / */ "010100010",
       /* + */ "010001010",
       /* % */ "000101010",
       /* * */ "010010100"
  };


  strSource = strSource.ToUpper();

  //實作圖片
  Bitmap objBitmap = new Bitmap(
    ((WidLength * 3 + NarrowLength * 7) * (intSourceLength + 2)) + (x * 2),
    BarCodeHeight + (y * 2));

  Graphics objGraphics = Graphics.FromImage(objBitmap); //宣告GDI+繪圖介面

  //填上底色
  objGraphics.FillRectangle(Brushes.White, 0, 0, objBitmap.Width, objBitmap.Height);

  for (int i = 0; i < intSourceLength; i++)
  {
    if (AlphaBet.IndexOf(strSource[i]) == -1 || strSource[i] == '*') //檢查是否有非法字元
    {
      objGraphics.DrawString("含有非法字元", SystemFonts.DefaultFont, Brushes.Red, x, y);
      return objBitmap;
    }
    //查表編碼
    strEncode = string.Format("{0}0{1}", strEncode, Code39[AlphaBet.IndexOf(strSource[i])]);
  }

  strEncode = string.Format("{0}0010010100", strEncode); //補上結束符號 *

  int intEncodeLength = strEncode.Length; //編碼後長度
  int intBarWidth;

  for (int i = 0; i < intEncodeLength; i++) //依碼畫出Code39 BarCode
  {
    intBarWidth = strEncode[i] == '1' ? WidLength : NarrowLength;
    objGraphics.FillRectangle(i % 2 == 0 ? Brushes.Black : Brushes.White,
      x, y, intBarWidth , BarCodeHeight);
    x += intBarWidth;
  }
  return objBitmap;
}

2014年7月25日 星期五

II7 搞定 web.config 設定值

當採用 vs 2008 開發 asp.net ,預帶的 web.config 會無法掛到 IIS7 上
必須調整 web.config 的宣告設定值
參考項:
Default Document
<configuration>
   <system.webServer>
      <defaultDocument enabled="true">
         <files>
            <add value="home.html" />
         </files>
      </defaultDocument>
   </system.webServer>
</configuration> 
--
底下為調整後的 web.config

vbnet 列印 QR Code 好用的工具

官網 qrencode-win32
--
試了一大堆 for .net dll QRcode ,結果都是密度 dpi 不夠!
要開發電子發票,根本行不通
試了一下  qrencode-win32 , 果然可以用!! 轉出 41x41 或 82x82 縮小 1.7cm 均可掃出來!
不過這套用在程式,目前採用 .bat 批次檔去產QRcode 圖! 為 big5 格式!
若採用 process 呼叫丟值的話,不知道是不是就變 UTF-8 格式! 有待測試
--
還在為開發電子發票QRcode的,改用這支工具來用

總算看到支援UTF-8了!!
qrencode-win32- UTF-8
指令: qrcode -o my.png -s 5 -l Q < input.txt
---
OT: qrcode--參數用法

參數:
C:\Program Files (x86)\QRCodeGui>qrcode
qrencode version 3.1.1
Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi
Usage: qrencode [OPTION]... [STRING]
Encode input data in a QR Code and save as a PNG image.

   -h           display this message.
   --help       display the usage of long options.
   -o FILENAME  write PNG image to FILENAME. If '-' is specified, the result
                will be output to standard output. If -S is given,
structured
                symbols are written to FILENAME-01.png, FILENAME-02.png,
...;
                if specified, remove a trailing '.png' from FILENAME.
   -s NUMBER    specify the size of dot (pixel). (default=3)
   -l {LMQH}    specify error collectin level from L (lowest) to H
(highest).
                (default=L)
   -v NUMBER    specify the version of the symbol. (default=auto)
   -m NUMBER    specify the width of margin. (default=4)
   -S           make structured symbols. Version must be specified.
   -k           assume that the input text contains kanji (shift-jis).
   -c           encode lower-case alphabet characters in 8-bit mode.
(default)
   -i           ignore case distinctions and use only upper-case characters.
   -8           encode entire data in 8-bit mode. -k, -c and -i will be
ignored.
   -V           display the version number and copyrights of the qrencode.
   [STRING]     input data. If it is not specified, data will be taken from
                standard input.

C:\Program Files (x86)\QRCodeGui>

2014年7月24日 星期四

vb.net Datatable group by with linq

參考引用來源:Datatable group by with linq in vb.net
--
Dim query = From row In dt
        Group row By Month = row.Field(Of Int32)("Month") Into MonthGroup = Group
        Select New With {
            Key Month,
            .Sales = MonthGroup.Sum(Function(r) r.Field(Of Int32)("Sales")),
            .Leads = MonthGroup.Sum(Function(r) r.Field(Of Int32)("Leads")),
            .Gross = MonthGroup.Sum(Function(r) r.Field(Of Int32)("Gross"))
       }

For Each x In query
    Console.WriteLine("Month:{0} {1} {2} {3}", x.Month, x.Sales, x.Leads, x.Gross)
Next

--
from b in db.Company
group b by b.Name into grp
where grp.Count() > 1
select grp.Key

How to print raw ESC/POS commands from ASP.NET directly to the client printer

請參考來源:How to print raw ESC/POS commands from ASP.NET directly to the client printer
--

2014年7月23日 星期三

利用Byte單位來計算字串長度

參考來源:利用Byte單位來計算字串長度的幾種做法(Javascript,C#,VB.Net)
--
 System.Text.Encoding.Default.GetBytes(str).Length

asp.net mssql add/edit/delete sample

參考範例:Add/Edit/Delete in ASP.NET(VB) - MS SQL Server
--
基本顯示資料:Connect to MS SQL Database using ASP.NET
--
習題] 補充上集Ch.14--自己撰寫SqlDataSource「新增資料」,並採用參數(InsertParameters)

預設 web.config 為 .NET 3.5  版本
所以在IIS 內要設定 3.5 或更高版本,才能運作


asp.net web.config 設定 sql 連線字串

參考引用來源:Store connection string in web.config
--

Store connection string in web.config

Connection string in .NET 2.0 config file
In the appSettings location, add a key named whatever you like to reference your connection string to.

<appSettings>
<add key="myConnectionString" value="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</appSettings>
To read the connection string from code, use the ConfigurationSettings class.

string connStr = ConfigurationSettings.AppSettings("myConnectionString");
Now you have the connection string loaded from web.config into your string variable in code.

Connection string in .NET 3.5 (and above) config file
Do not use appsettings in web.config. Instead use the connectionStrings section in web.config.

<connectionStrings>
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>
To read the connection string into your code, use the ConfigurationManager class.

string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;

2014年7月21日 星期一

行政院人事行政總處 全球資訊網

行政院人事行政總處 全球資訊網
--

SQL 日期時間轉換


SQL 日期時間轉換

MS SQL
YYYY-MM-DD (2008-06-26):CONVERT(CHAR(10), GETDATE(), 120)
HH:MM:SS:sss (17:24:30):CONVERT(CHAR(8), GETDATE(), 114)

MM DD YYYY (06 26 2008):CONVERT(CHAR(10), GETDATE(), 100)
MM/DD/YYYY (06/26/2008):CONVERT(CHAR(10), GETDATE(), 101)
MM.DD.YYYY (06.26.2008):CONVERT(CHAR(10), GETDATE(), 102)

DD/MM/YYYY (14/03/2011):CONVERT(CHAR(10), GETDATE(), 103)
DD.MM.YYYY (14.03.2011):CONVERT(CHAR(10), GETDATE(), 104)
DD-MM-YYYY (14-03-2011):CONVERT(CHAR(10), GETDATE(), 105)
DD MM YYYY (14 03 2011):CONVERT(CHAR(10), GETDATE(), 106)

YYYYMMDD (20110314):CONVERT(CHAR(8), GETDATE(), 112)
HH:MM:SS:sss (17:24:30:923):CONVERT(CHAR(12), GETDATE(), 114)


Sybase
YYYYMMDD (20080626):CONVERT(CHAR(10), GETDATE(), 112)
YYYY/MM/DD (2008/11/24):CONVERT(CHAR(10), GETDATE(), 111)
MM-DD-YYYY (11-24-2008):CONVERT(CHAR(10), GETDATE(), 110)
HH:mm:SS (15:49:34):CONVERT(CHAR(10), GETDATE(), 108)


MySQL
select DATE_FORMAT(now(), '%Y-%m-%d');
select DATE_FORMAT(now(), '%T');

use DATE_FORMAT(date,format)

format 格式如下:

%Y 年 YYYY ex:2011
%y 年 yy ex:11

%a 星期 英文縮寫名稱 ex:Fri
%b 月 英文縮寫名稱 ex:Feb
%M 月 英文全名 ex:February
%c 月 數值 ex:2 (二月)
%m 月 數值(00-12)

%D 日 數值 加英文首碼 ex:3rd, 20th
%d 日 數值 補零 ex:(00-31)
%e 日 數值 補零 ex:(0-31)
%j 一年的第幾天 (001-366)

%r 時間 小時12(hh:mm:ss AM 或 PM)ex:10:05:54 PM
%T 時間 小時24 (hh:mm:ss)

%H 小時24 補零 (00-23)
%h 小時12 補零 (01-12)
%k 小時24 (0-23)
%l 小時12 (1-12)
%i 分鐘 補零 (00-59)
%S 秒(00-59)
%s 秒(00-59)

%f 微秒
%p AM 或 PM

%U 周 (00-53) 星期日是一周的第一天
%u 周 (00-53) 星期一是一周的第一天
%V 周 (01-53) 星期日是一周的第一天,與 %X 使用
%v 周 (01-53) 星期一是一周的第一天,與 %x 使用
%W 星期名
%w 周的天 (0=星期日, 6=星期六)
%X 年,其中的星期日是周的第一天,4 位,與 %V 使用
%x 年,其中的星期一是周的第一天,4 位,與 %v 使用

Microsoft Point of Service for .NET

下載:Microsoft Point of Service for .NET v1.12 (POS for .NET) 
下載:Microsoft Point of Service for .NET v1.14 (POS for .NET) (Win 8.1)
 

QR codes are defined in versions

QR codes are defined in "versions" 
--

2014年7月20日 星期日

Get IP address by domain name


Imports System.Net
Imports System.Net.Sockets


Public Class Tester
    Public Shared Sub Main


        Try
            Dim myIPHostEntry As IPHostEntry = Dns.Resolve("www.google.com")
            Dim myIPAddresses() As IPAddress = myIPHostEntry.AddressList
            Dim myIPAddress As IPAddress

            Dim strIPAddressList As String

            For Each myIPAddress In myIPAddresses

                Console.WriteLine(myIPAddress.ToString)

            Next
        Catch ex As SocketException
            Console.WriteLine(ex.Message)
        End Try

    End Sub
End Class

2014年7月16日 星期三

printing QR codes through an ESC/POS thermal printer

參考引用來源:printing QR codes through an ESC/POS thermal printer
--


def test_qrcode (printer, text, print_also_text=false, qr_size=6.chr)

  s = text.size + 3
  lsb = (s % 256).chr
  msb = (s / 256).chr

  # https://code.google.com/p/python-escpos/wiki/Usage
  escpos = ""
  escpos << "\x1D\x28\x6B\x03\x00\x31\x43#{qr_size}"
  escpos << "\x1D\x28\x6B\x03\x00\x31\x45\x33"
  escpos << "\x1D\x28\x6B#{lsb}#{msb}\x31\x50\x30"
  escpos << text #
  escpos << "\x1D\x28\x6B\x03\x00\x31\x51\x30"

  # writing byte streams directly to the serial port
  printer.write escpos

end

電子天平透過RS232連線讀值

參考引用來源:電子天平透過RS232連線讀值
--
1.前言
以程式遠端讀取電子天平秤重數值,可將資料存檔紀錄歷史數據。

2.說明
本範例是針對Precisa Balances進行RS232遠端連線控制儀器,首先要做一條RJ45轉RS232的連接線(儀器端為RJ45接口,電腦端為RS232接口),RJ45端口接線配置與遠端控制的命令可參考原廠的操作說明書,這裡舉PRINT控制命令做說明。
PRT: Start printing(Press "Print" key)

加入命名空間

?
1
using System.IO.Ports;
加入serialPort,設定屬性

BaudRate:9600
DataBits:8
Parity:None
StopBits:One
Form_Load加入資料接收處理事件

private void Form1_Load(object sender, EventArgs e)
{
    serialPort1.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
}

private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    System.Threading.Thread.Sleep(100);
    string message = serialPort1.ReadExisting();
    SaveData(message);
}
儲存資料

private void SaveData(string message)
{
    string _sign = "";
    double _weight = 0;
    string _unit = "";
    string _datetime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
    _sign = message.Substring(3, 1);
    if (_sign == "-") _weight = -double.Parse(message.Substring(4, 9));
    if (_sign == "+") _weight = double.Parse(message.Substring(4, 9));
    _unit = message.Substring(15, 3);
    Console.WriteLine(_weight.ToString());
}
傳送命令

private void SendCommand(string command)
{
    serialPort1.Write(command);
}
遠端下控制命令
string cmd = "PRT\r\n";
SendCommand(cmd);

利用GDI+繪製條碼(Code 39)標籤

參考引用來源:利用GDI+繪製條碼(Code 39)標籤
--
1.前言:
在生產系統中,需要用到大量的條碼標籤列印,本範例利用GDI+繪圖的方式,產生條碼的圖檔,可供列印條碼標籤。

2.說明:
條碼的基本說明可參考
http://en.wikipedia.org/wiki/Barcode
本範例介紹Code39條碼,其相關資訊請參考
http://en.wikipedia.org/wiki/Code_39

建立CodeSystem類別

public class CodeSystem
{
    public static Hashtable Code39()
    {
        Hashtable code = new Hashtable();

        code.Add("0", "bwbWBwBwb");
        code.Add("1", "BwbWbwbwB");
        code.Add("2", "bwBWbwbwB");
        code.Add("3", "BwBWbwbwb");
        code.Add("4", "bwbWBwbwB");
        code.Add("5", "BwbWBwbwb");
        code.Add("6", "bwBWBwbwb");
        code.Add("7", "bwbWbwBwB");
        code.Add("8", "BwbWbwBwb");
        code.Add("9", "bwBWbwBwb");
        code.Add("A", "BwbwbWbwB");
        code.Add("B", "bwBwbWbwB");
        code.Add("C", "BwBwbWbwb");
        code.Add("D", "bwbwBWbwB");
        code.Add("E", "BwbwBWbwb");
        code.Add("F", "bwBwBWbwb");
        code.Add("G", "bwbwbWBwB");
        code.Add("H", "BwbwbWBwb");
        code.Add("I", "bwBwbWBwb");
        code.Add("J", "bwbwBWBwb");
        code.Add("K", "BwbwbwbWB");
        code.Add("L", "bwBwbwbWB");
        code.Add("M", "BwBwbwbWb");
        code.Add("N", "bwbwBwbWB");
        code.Add("O", "BwbwBwbWb");
        code.Add("P", "bwBwBwbWb");
        code.Add("Q", "bwbwbwBWB");
        code.Add("R", "BwbwbwBWb");
        code.Add("S", "bwBwbwBWb");
        code.Add("T", "bwbwBwBWb");
        code.Add("U", "BWbwbwbwB");
        code.Add("V", "bWBwbwbwB");
        code.Add("W", "BWBwbwbwb");
        code.Add("X", "bWbwBwbwB");
        code.Add("Y", "BWbwBwbwb");
        code.Add("Z", "bWBwBwbwb");
        code.Add("-", "bWbwbwBwB");
        code.Add(".", "BWbwbwBwb");
        code.Add(" ", "bWBwbwBwb");
        code.Add("$", "bWbWbWbwb");
        code.Add("/", "bWbWbwbWb");
        code.Add("+", "bWbwbWbWb");
        code.Add("%", "bwbWbWbWb");
        code.Add("*", "bWbwBwBwb");

        return code;
    }
}
建立Code39影像檔方法

private Bitmap Code39(string strInput)
{
    //Code 39 specification
    int narrowWidth = 1;
    int wideWidth = 2;
    int B = wideWidth;//Wide-Black width
    int b = narrowWidth;//Narrow-Black width
    int W = wideWidth;//Wide-White width
    int w = narrowWidth;//Narrow-White width          
    int padding = 15;
    int startPoint = padding;//繪製線條起點
    int strLength = strInput.Length;
    FontFamily fontFamily = new FontFamily("Arial");
    Font myFont = new Font(fontFamily, 9, FontStyle.Regular, GraphicsUnit.Point);
    int barcodeHeight = 60;
    int barcodeWidth = (wideWidth * 3 + narrowWidth * 7) * (strLength + 2); ;

    //定義影像檔
    /*寬度設定定義:
      以A為例,code為BwbwbWbwB加上結尾w共十個字元,其中寬線共三個,窄線共7個;
      字串長度加上前後的*;
      前後留白的寬度x2
    */
    int imgWidth = ((wideWidth * 3 + narrowWidth * 7) * (strLength + 2)) + padding * 2;
    int imgHeight = barcodeHeight + padding * 2;
    pictureBox1.Width = imgWidth;
    pictureBox1.Height = imgHeight;
    Bitmap bitmap = new Bitmap(imgWidth, imgHeight);
    //在image上繪圖
    Graphics g = Graphics.FromImage(bitmap);
    g.PageUnit = GraphicsUnit.Pixel;
    //繪圖品質設定
    g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
    g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
    g.CompositingQuality = CompositingQuality.HighQuality;
    g.SmoothingMode = SmoothingMode.AntiAlias;
    g.InterpolationMode = InterpolationMode.High;
    g.PixelOffsetMode = PixelOffsetMode.HighQuality;
    //先將背景色設定為白色
    g.FillRectangle(new SolidBrush(Color.White), 0, 0, bitmap.Width, bitmap.Height);

    string codeString = "";
    Hashtable getCode = CodeSystem.Code39();

    for (int i = 0; i < strInput.Length; i++)
    {
        string character = strInput[i].ToString().ToUpper();
        if (getCode[strInput[i].ToString().ToUpper()] != null && getCode[strInput[i].ToString().ToUpper()].ToString() != "*")
        {
            codeString += getCode[strInput[i].ToString().ToUpper()].ToString() + "w";
        }
        else
        {
            g.DrawString("Invalid\nCharacter", myFont, Brushes.Black, 0, (barcodeHeight + padding * 2) / 3);
            return bitmap;
        }
    }
    //前後用*包起字串,例如*Code39*
    codeString = getCode["*"].ToString() + "w" + codeString + getCode["*"].ToString();
    Console.WriteLine(codeString);
    int shiftPoint = 0;
    for (int i = 0; i < codeString.Length; i++)
    {
        string s = codeString[i].ToString();

        switch (s)
        {
            case "B":
                shiftPoint = B;
                break;
            case "b":
                shiftPoint = b;
                break;
            case "W":
                shiftPoint = W;
                break;
            case "w":
                shiftPoint = w;
                break;
        }

        g.FillRectangle(i % 2 == 0 ? new SolidBrush(Color.Black) : new SolidBrush(Color.White), startPoint, padding, shiftPoint, barcodeHeight);
        startPoint += shiftPoint;
    }

    //Draw footer string
    string footerString = "*" + strInput + "*";
    //g.DrawString(footerString, myFont, Brushes.Black, (float)(padding / 2f + imgWidth / 2f - (footerString.Length * myFont.Size / 2f)), (float)(barcodeHeight + padding + 2f));
    TextRenderer.DrawText(g, footerString, myFont, new Point((int)(padding / 2f + imgWidth / 2f - (footerString.Length * myFont.Size / 2f)), (int)(barcodeHeight + padding + 2f)), SystemColors.ControlText);

    return bitmap;
}
3.應用:

//定義影像檔
Bitmap bitmap = Code39("PIXNET");
//顯示影像
pictureBox1.Image = bitmap;

使用LinqToExcel讀取Excel 2003/2007檔案


參考引用來源:使用LinqToExcel讀取Excel 2003/2007檔案
--

1.前言:
讀取Excel檔案的方法很多,LinqToExcel是利用Linq的方式查詢讀取Excel 2003/2007的檔案,為一個MIT license的開放程式碼函式庫。

2.說明:
與眾多操作Excel檔案的函式庫相比,LinqToExcel只能算是輕量級的軟體,用以單純讀取Excel檔案。

有關LinqToExcel的說明可參考:
https://github.com/paulyoder/LinqToExcel#welcome-to-the-linqtoexcel-project

LinqToExcel軟體下載網址:
http://code.google.com/p/linqtoexcel/

本範例使用版本為LinqToExcel_1.7.1,建置平台選擇x86模式。
軟體解壓縮後,將\LinqToExcel_1.7.1的DLL檔複製到自己專案的bin目錄下

加入參考: LinqToExcel.dll, Remotion.Data.Linq.dll
加入命名空間:

using LinqToExcel;
using Remotion;

Excel轉成DataTable:


private DataTable ExcelToDataTable(string filePath, string sheetName)
{
    DataTable dt = new DataTable();
    ExcelQueryFactory excel = new ExcelQueryFactory(filePath);
    IQueryable query = from row in excel.Worksheet(sheetName) select row;

    var columnName = excel.GetColumnNames(sheetName);

    //建立欄位名稱
    foreach (var col in columnName)
    {
        dt.Columns.Add(col.ToString());
    }

    //寫入資料到資料列
    foreach (Row item in query)
    {
        dt.NewRow();
        object[] cell = new object[columnName.Count()];
        int idx = 0;
        foreach (var col in columnName)
        {
            cell[idx] = item[col].Value;
            idx++;
        }
        dt.Rows.Add(cell);
    }          

    return dt;
}
3.應用:

//範例一: 讀取Excel 2003檔案
string filePath = @"D:\tmp\b.xls";
string sheetName = "Sheet1";
DataTable dt = ExcelToDataTable(filePath, sheetName);
//範例二: 讀取Excel 2007檔案
string filePath = @"D:\tmp\c.xlsx";
string sheetName = "Sheet1";
DataTable dt = ExcelToDataTable(filePath, sheetName);

C#中利用DataTable.Compute()方法對資料欄位做數值計算

參考引用來源:C#中利用DataTable.Compute()方法對資料欄位做數值計算
--



1.前言:
如果要對DataTable中的特定欄位做資料分析,在不使用其他第三方函式庫的情況下,可以用Compute方法來做基本的數值計算。

2.說明:
用法: DataTable.Compute( string expression, string filter)
支援以下聚合函數:
•Sum (Sum)
•Avg (Average)
•Min (Minimum)
•Max (Maximum)
•Count (Count)
•StDev (Statistical standard deviation)
•Var (Statistical variance)
使用上要注意的是欄位的型態需要是數值型態,如果是字串型態,可以簡單定義一個新欄位為數值型,再複製要計算的欄位資料做資料分析,否則會出現彙總函式和型別的無效用法: String錯誤訊息。

有關DataTable.Compute()的說明可參考:
http://msdn.microsoft.com/en-us/library/system.data.datatable.compute(v=vs.100).aspx

程式碼:

private void btCalc_Click(object sender, EventArgs e)
{
    double mean, stdev, max, min, variance, count, sum;
    DataTable dt = TxtConvertToDataTable(@"d:\tmp\dt.csv", "tmp", ",");//讀取資料

    dt.Columns.Add("tmpColumn", typeof(double), "Convert(data, 'System.Double')");//加入暫存欄位,將資料中string的型態轉為double型態

    mean = (double)dt.Compute("Avg(tmpColumn)", string.Empty);
    stdev = (double)dt.Compute("Stdev(tmpColumn)", string.Empty);
    max = (double)dt.Compute("Max(tmpColumn)", string.Empty);
    min = (double)dt.Compute("Min(tmpColumn)", string.Empty);
    variance = (double)dt.Compute("Var(tmpColumn)", string.Empty);
    count = (int)dt.Compute("Count(tmpColumn)", string.Empty);
    sum = (double)dt.Compute("Sum(tmpColumn)", string.Empty);

    dt.Columns.Remove("tmpColumn");//移除暫存欄位      
   
    MessageBox.Show("Mean: "+mean+"\r\n"
        + "Stdev: " + stdev + "\r\n"
        + "Max: " + max + "\r\n"
        + "Min: " + min + "\r\n"
        + "Variance: " + variance + "\r\n"
        + "Count: " + count + "\r\n"
        + "Sum: " + sum + "\r\n"
        );
}

public DataTable TxtConvertToDataTable(string File, string TableName, string delimiter)
{
    DataTable dt = new DataTable();
    DataSet ds = new DataSet();
    StreamReader s = new StreamReader(File, System.Text.Encoding.Default);
    string[] columns = s.ReadLine().Split(delimiter.ToCharArray());
    ds.Tables.Add(TableName);
    foreach (string col in columns)
    {
        bool added = false;
        string next = "";
        int i = 0;
        while (!added)
        {
            string columnname = col + next;
            columnname = columnname.Replace("#", "");
            columnname = columnname.Replace("'", "");
            columnname = columnname.Replace("&", "");

            if (!ds.Tables[TableName].Columns.Contains(columnname))
            {
                ds.Tables[TableName].Columns.Add(columnname.ToUpper());
                added = true;
            }
            else
            {
                i++;
                next = "_" + i.ToString();
            }
        }
    }

    string AllData = s.ReadToEnd();
    string[] rows = AllData.Split("\n".ToCharArray());

    foreach (string r in rows)
    {
        string[] items = r.Split(delimiter.ToCharArray());
        ds.Tables[TableName].Rows.Add(items);
    }

    s.Close();

    dt = ds.Tables[0];

    return dt;
}

使用ExcelDataReader讀取Excel 2007檔案

參考引用來源:使用ExcelDataReader讀取Excel 2007檔案
--


1.前言:
ExcelDataReader是一個MIT license的開放原始碼的函式庫,可以用來讀取Excel 2007檔案。

2.說明:
ExcelDataReader的說明及軟體下載網址:
http://exceldatareader.codeplex.com/

本範例使用版本為ExcelDataReader v2.1(Beta)
軟體解壓縮後,將\2.1.beta.binary\Excel.dll的DLL檔複製到自己專案的bin目錄下

加入參考: Excel.dll
加入命名空間:

using Excel;
程式碼:
string filePath = @"d:\tmp\c.xlsx";
FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);//Excel 2007格式; *.xlsx
excelReader.IsFirstRowAsColumnNames = true;
DataSet ds = excelReader.AsDataSet(); //所有的頁簽資料存在ds.Tables中
excelReader.Close();
dataGridView1.DataSource = ds.Tables[1];

使用NBarcodes產生一維條碼圖形

參考引用來源:使用NBarcodes產生一維條碼圖形
--
1.前言:
NBarcodes是一個MIT license的開放函式庫,用來製作一維條碼。

2.說明:
NBarcodes的說明可參考及軟體下載網址:
http://code.google.com/p/nbarcodes/

條碼編碼支援類型:
Code 128, Code 39, Standard 2 of 5, Interleaved 2 of 5, EAN-13, EAN-8, UPC-A, UPC-E and Postnet

本範例使用版本為nbarcodes-v1.0.0
軟體解壓縮後,將\nbarcodes-v1.0.0-bin\NBarCodes.dll的DLL檔複製到自己專案的bin目錄下

加入參考: NBarCodes.dll
加入命名空間:

using NBarCodes;
程式碼:
//產生Code128
NBarCodes.Forms.BarCodeControl bc = new NBarCodes.Forms.BarCodeControl();
bc.Type = BarCodeType.Code128;
bc.Data = "PIXNET";
bc.Visible = true;
BarCodeGenerator generator = new BarCodeGenerator(bc);
Image image = generator.GenerateImage();
pictureBox1.Image = image;


使用ZXing.Net產生一維/二維條碼圖形

參考引用來源:使用ZXing.Net產生一維/二維條碼圖形
--

分享:    
1.前言:
ZXing.Net是一個Apache License 2.0的開放函式庫,可以輕鬆地製作一維及二維條碼,讓專案報表開發更快速。

2.說明:
ZXing.Net的說明及軟體下載網址:
http://zxingnet.codeplex.com/

條碼解碼支援類型:
UPC-A, UPC-E, EAN-8, EAN-13, Code 39, Code 93, Code 128, ITF, Codabar, MSI, RSS-14 (all variants), QR Code, Data Matrix, Aztec and PDF-417.
條碼編碼支援類型:
UPC-A, EAN-8, EAN-13, Code 39, Code 128, ITF, Codabar, Plessey, MSI, QR Code, PDF-417, Aztec, Data Matrix

本範例使用版本為ZXing.Net.0.12.0.0
軟體解壓縮後,將\ZXing.Net.0.12.0.0\net3.5\zxing.dll的DLL檔複製到自己專案的bin目錄下

加入參考: zxing.dll
加入命名空間:
using ZXing;
程式碼:

//範例一: 產生QRCode
BarcodeWriter bw = new BarcodeWriter();
bw.Format = BarcodeFormat.QR_CODE;
bw.Options.Width = 260;
bw.Options.Height = 237;
Bitmap bitmap = bw.Write("PIXNET");
pictureBox1.Image = (Image)bitmap;

//範例二: 產生Code128
BarcodeWriter bw = new BarcodeWriter();
bw.Format = BarcodeFormat.CODE_128;
bw.Options.Width = 200;
bw.Options.Height = 100;
bw.Options.PureBarcode = false;
Bitmap bitmap = bw.Write("PIXNET");
pictureBox1.Image = (Image)bitmap;

利用QrCode.Net來創建二維條碼圖形

參考引用來源:利用QrCode.Net來創建二維條碼圖形
--


1.前言:
傳統的一維條碼圖能記錄的資訊有限,而二維的條碼圖可記錄大量訊息,另外QR碼有容錯能力,可降低因為標籤部分磨損無法判讀的問題。本範例在利用open source的軟體,來建立QRCode的影像圖形。


2.說明:
QrCode.Net是一個MIT license的開放軟體,軟體最新版本可在下列網址下載:
本範例使用的版本為: 0.4 Pre-release
http://qrcodenet.codeplex.com/

QRCode的說明可參考以下網址:
http://en.wikipedia.org/wiki/QR_code

將軟體下載後解壓縮,在Gma.QrCodeNet.Encoding.Net35目錄下複製Gma.QrCodeNet.Encoding.Net35.dll到自己的專案bin目錄下。

加入參考:
Gma.QrCodeNet.Encoding.Net35.dll
加入命名空間:

using Gma.QrCodeNet.Encoding;
using Gma.QrCodeNet.Encoding.Windows.Render;
程式碼:

//輸入要製作二維條碼的字串
string codeString = "http://einboch.pixnet.net/blog";

//實例化,設定錯誤修正容量
/*
  Level L (Low)      7%  of codewords can be restored.
  Level M (Medium)   15% of codewords can be restored.
  Level Q (Quartile) 25% of codewords can be restored.
  Level H (High)     30% of codewords can be restored.
*/
QrEncoder encoder = new QrEncoder(ErrorCorrectionLevel.L);

//編碼
QrCode code = encoder.Encode(codeString);

//定義線條寬度
int moduleSizeInPixels = 12;

//繪二維條碼圖初始化
GraphicsRenderer renderer = new GraphicsRenderer(new FixedModuleSize(moduleSizeInPixels, QuietZoneModules.Two), Brushes.Black, Brushes.White);

//留白區大小
Point padding = new Point(10, 16);

//取得條碼圖大小
DrawingSize dSize = renderer.SizeCalculator.GetSize(code.Matrix.Width);
int imgWidth = dSize.CodeWidth + 2 * padding.X;
int imgHeight = dSize.CodeWidth+2 * padding.Y;
//設定影像大小
Image img = new Bitmap(imgWidth, imgHeight);
pictureBox1.Width = imgWidth;
pictureBox1.Height = imgHeight;
//繪製二維條碼圖
Graphics g = Graphics.FromImage(img);
renderer.Draw(g, code.Matrix, padding);

pictureBox1.Image = img;

ADO.NET MSSQL

請參考:SQL Helper Class

2014年7月15日 星期二

Get connection string from app.config file

參考引用:Get connection string from app.config file 
---

參考 ConfigurationManager
引入 System.Configuration

Private cn As New SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("StorkConnection").ConnectionString)

...
app.config



   
   
   
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=C:\database.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"providerName="System.Data.SqlClient"/>
   



2014年7月12日 星期六

mssql datetime 查询 (mssql 2008 r2 bug)

相關參考:[SQL SERVER][Memo]搜尋datetime類型欄位三兩事
--
今天MSSQL DB 發生一件怪事 !
竟然查 datetime 欄位,竟查不到資料....真不敢相信,以前一直這樣使用!
例:
select * from abc where gdate='2014/7/12'

gdate type datetime

(上例)以前這樣查,均可正常顯示資料出來! 但現在竟查不出來
納悶.......不相信,我使用另一個資料庫;使用上面的查法,能查出來啊...(天啊)
why ...到底是發生什麼事!  A 資料庫查不出日期 , B 資料庫卻查出日期
---
只好當這問題是 MSSQL 2008 R2 Express 的 bug...

解決方式:
MSSQL 服務重新啟動後 , 即可正常!!  (真是天大的bug..用這麼多年,這一次發生)

2014年7月6日 星期日

vb.net set mouse pointer position

參考來源:Cursor.Position 屬性
--
Me.Cursor = New Cursor(Cursor.Current.Handle)
Cursor.Position = New Point(0, 0)

vbnet check date format yyyyMMdd

參考引用來源:checking if string is a date in yyyyMMdd format
--
Dim ds As String = "20140706"
Dim dt As DateTime
If DateTime.TryParseExact(ds, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture, _
      DateTimeStyles.None, dt) Then
   MessageBox.Show("Date is " & dt.ToString)
Else
   MessageBox.Show("Invalid date")
End If

2014年7月1日 星期二

池龍工作室

(永久網址) 已註冊網址 :  http://www.wushi.idv.tw/  進入:池龍工作室

說明:
由於微軟把 no-ip 所有免費的網址都撤銷,導致現在 no-ip 無法導引到網站!
相關請參考本篇 no-ip 官網發佈的資料 No-IP’s Formal Statement on Microsoft Takedown

--
看來,還是要付費的較沒問題!!
hinet 網域名稱申請服務
TWNIC-財團法人台灣網路資訊中心