2011年5月30日 星期一

Lesson 1 for Flex 4.5

1. Flex in a week traning kit seems can not work directly in the version 4.0 applied in the begining of this year.
2. Apply version 4.5 as follows;
2.1 Apply for free educational version ( The faculty ID will be needed)


2.2 Waiting for some days, the serial number will send to your email account. Installing

2.3 Download examples code(s)


3. Testing for examples in day 1
3.1 Open Flex builder and switch workspace into the folder storing those unzip files
3.2 Play ex1_02

2011年5月28日 星期六

emgu WPF

Emgu in WPF example
1. Add reference
    Emgu.CV.dll
    Emgu.CV.UI.dll
    Emgu.Util.dll
2. namespace
    //---------------------
using System.IO;
using Emgu.CV;
using Emgu.CV.UI;
using Emgu.CV.Structure;
using Emgu.Util;
using System.Threading;
using System.Timers;
using System.Runtime.InteropServices;
using System.Windows.Threading;
3. Window1.xaml
3.1 Set window load and closing events: Loaded="Window_Loaded" Closing="Window_Closing"
3.2 Build Image tag (Testing rendering functions)
<Image x:Name="webcam" Width="640" Height="480" >
            <Image.Clip>
                <EllipseGeometry  RadiusX="240" RadiusY="240">
                    <EllipseGeometry.Center>
                        <Point X="320" Y="240" />
                    </EllipseGeometry.Center>
                </EllipseGeometry>
            </Image.Clip>
            <Image.RenderTransform>
                <RotateTransform Angle="15"></RotateTransform>
            </Image.RenderTransform>
        </Image>
4. Wndow1.xaml.cs
        private Capture capture;
        private DispatcherTimer timer;
        //ImageBox im = new ImageBox();
        /// <summary>
        /// Window1.xaml 的互動邏輯
        /// </summary>
        [DllImport("gdi32")]
        private static extern int DeleteObject(IntPtr o);
        /// <summary>
        /// Convert an IImage to a WPF BitmapSource. The result can be used in the Set Property of Image.Source
        /// </summary>
        /// <param name="image">The Emgu CV Image</param>
        /// <returns>The equivalent BitmapSource</returns>
        public static BitmapSource ToBitmapSource(IImage image)
        {
            using (System.Drawing.Bitmap source = image.Bitmap)
            {
                IntPtr ptr = source.GetHbitmap(); //obtain the Hbitmap
                BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                    ptr,
                    IntPtr.Zero,
                    Int32Rect.Empty,
                    System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                DeleteObject(ptr); //release the HBitmap
                return bs;
            }
        }

5. Form_load and timer event methods
private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //G1.Children.Add(im);
            capture = new Capture();
            capture.FlipHorizontal = true;
            timer = new DispatcherTimer();
            timer.Interval = new TimeSpan(150000); // 150000 x 100 ns  = 1.5 E-4 s 15 ms
            //timer.Interval = 15;
            timer.Tick += new EventHandler(timer_Tick);
            //timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
            timer.Start();
        }
        void timer_Tick(object sender, EventArgs e)
        {
            using (Image<Bgr, byte> frame = capture.QueryFrame())
            {
                if (frame != null)
                {
                    //var bmp = frame.Bitmap;
                    // How do I pass this bitmap to my Image control called "webcam"?
                    //webcam.Source = frame.Bitmap;
                    //MemoryStream ms = new MemoryStream();
                    //System.Drawing.Bitmap bmp = frame.Bitmap;
                    //bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                    //BitmapImage bi = new BitmapImage();
                    //bi.BeginInit();
                    //bi.StreamSource = ms;
                    //bi.EndInit();
                    webcam.Source = ToBitmapSource(frame);
                }
            }
        }
6. Window_Closing
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
             if (capture != null)
            {
                capture.Dispose();
            }
        }

2011年5月26日 星期四

DotNET Connection Strings

Connection String
1. Access 2003
Provider=Microsoft.Jet.OLEDB.4.0; Data Source=myData.mdb;
2. Excel 2003
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=MyExcel.xls; Extended Properties=""Excel 8.0; HDR=Yes;IMEX=1""
3. SQL 2008 R2
Data Source=192.168.xxx.ooo\JOUSQL2008R2;Initial Catalog=HWC991;User ID=Web9912;Password=xxx9912x
4. Access 2007
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\myFolder\myAccess2007file.accdb;Persist Security Info=False;
5. Excel 2007
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myExcel2007file.xlsx;Extended Properties="Excel 12.0 Xml;HDR=YES";
6. MySQL
using MySql.Data.MySqlClient;
string strConn = "Server=192.168.xxx.ooo;Uid=Web9912;Pwd=HWC9912a;Database=test;";

ref: http://msdn.microsoft.com/zh-tw/library/system.data.odbc.odbcconnection.connectionstring(v=vs.80).aspx

ODBC Connection
7. SQL w/o testing
"Driver={SQL Server};Server=(local);Trusted_Connection=Yes;Database=AdventureWorks;"
8. Access 2003
"Driver={Microsoft Access Driver (*.mdb)};DBQ=c:\bin\Northwind.mdb"
9. Excel 2003
"Driver={Microsoft Excel Driver (*.xls)};DBQ=c:\bin\book1.xls"

10 Example shows both of Odbc and OleDb connecting to Excel file while DataAdapter and DataReader were used to get data table and data row repectively as follows:
using System.Data;
using System.Data.Odbc;
using System.Data.OleDb;
class getxls
        {
            static public DataTable OdbcGetTable(string SQL, string path1)
            {
                DataSet DS = new DataSet();
                OdbcConnection conn = new OdbcConnection("Driver={Microsoft Excel Driver (*.xls)};DBQ=" + path1);
                conn.Open();
                OdbcDataAdapter apt = new OdbcDataAdapter(SQL, conn);
                apt.Fill(DS);
                conn.Close();
                return DS.Tables[0];
            }
            static public DataTable OleDbGetTable(string SQL, string path1)
            {
                DataSet DS = new DataSet();
                OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path1 + "; Extended Properties='Excel 8.0; HDR=Yes;IMEX=1'");
                conn.Open();
                OleDbDataAdapter apt = new OleDbDataAdapter(SQL, conn);
                apt.Fill(DS);
                conn.Close();
                return DS.Tables[0];
            }
            static public string OleDbGetRow(string SQL, string path1)
            {
                DataSet DS = new DataSet();
                OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path1 + "; Extended Properties='Excel 8.0; HDR=Yes;IMEX=1'");
                OleDbCommand cmd = new OleDbCommand(SQL, conn);
                conn.Open();
                OleDbDataReader reader = cmd.ExecuteReader();
                //while (reader.Read())
                //{
                //    Console.WriteLine(reader.GetInt32(0) + ", " + reader.GetString(1));
                //}
                string out1 = "";
                while (reader.Read())
                {
                    int ct = reader.FieldCount;
                   
                    for (int i = 0; i < ct; i++)
                    {
                        out1 += reader.GetDouble(i).ToString() ;
                    }
                    out1 += ";";
                   
                }
                conn.Close();
                return out1 ;
            }
            static public string OdbcGetRow(string SQL, string path1)
            {
                DataSet DS = new DataSet();
                OdbcConnection conn = new OdbcConnection("Driver={Microsoft Excel Driver (*.xls)};DBQ=" + path1);
                OdbcCommand cmd = new OdbcCommand(SQL, conn);
                conn.Open();
                OdbcDataReader reader = cmd.ExecuteReader();
                //while (reader.Read())
                //{
                //    Console.WriteLine(reader.GetInt32(0) + ", " + reader.GetString(1));
                //}
                string out1 = "";
                while (reader.Read())
                {
                    int ct = reader.FieldCount;
                    for (int i = 0; i < ct; i++)
                    {
                        out1 += reader.GetDouble(i).ToString();
                    }
                    out1 += ";";
                }
                conn.Close();
                return out1;
            }
        }

2011年5月25日 星期三

Emgu: Integrated examples of CameraCapture and FaceDetection

Integrate to examples to generate face detection in continous images as follows:
1. Create a Windowform application
2. Add reference
3. Add using namespace
//--------
using Emgu.CV;
using Emgu.CV.Structure;
using Emgu.Util;
using Emgu.CV.UI;
4. Add a form load event method
        private Capture _capture;
        private bool _captureInProgress;
        ImageBox box = new ImageBox();
        private void Form1_Load(object sender, EventArgs e)
        {
            box.Width = 800;
            box.Height = 600;
            this.Controls.Add(box);
            //Application.Idle += new EventHandler(Application_Idle);
            #region if capture is not created, create it now
            if (_capture == null)
            {
                try
                {
                    _capture = new Capture();
                }
                catch (NullReferenceException excpt)
                {
                    MessageBox.Show(excpt.Message);
                }
            }
            #endregion
            if (_capture != null)
            {
                if (_captureInProgress)
                {  //stop the capture
                    Application.Idle -= Application_Idle;
                }
                else
                {
                    //start the capture
                    //captureButton.Text = "Stop";
                    Application.Idle += Application_Idle;
                }
                _captureInProgress = !_captureInProgress;
            }
        }
        void Application_Idle(object sender, EventArgs e)
        {
            Image<Bgr, Byte> frame = _capture.QueryFrame();
            box.Image = frame;
            //Image<Bgr, Byte> image = new Image<Bgr, byte>("lena.jpg"); //Read the files as an 8-bit Bgr image 
            Image<Gray, Byte> gray = frame.Convert<Gray, Byte>(); //Convert it to Grayscale
            //normalizes brightness and increases contrast of the image
            gray._EqualizeHist();
            //Read the HaarCascade objects
            HaarCascade face = new HaarCascade("../../haarcascade_frontalface_alt_tree.xml");
            HaarCascade eye = new HaarCascade("../../haarcascade_eye.xml");
            //Detect the faces  from the gray scale image and store the locations as rectangle
            //The first dimensional is the channel
            //The second dimension is the index of the rectangle in the specific channel
            MCvAvgComp[][] facesDetected = gray.DetectHaarCascade(face, 1.1, 1, Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(20, 20));
            foreach (MCvAvgComp f in facesDetected[0])
            {
                //Set the region of interest on the faces
                gray.ROI = f.rect;
                MCvAvgComp[][] eyesDetected = gray.DetectHaarCascade(eye, 1.1, 1, Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(20, 20));
                gray.ROI = Rectangle.Empty;
                //if there is no eye in the specific region, the region shouldn't contains a face
                //note that we might not be able to recoginize a person who ware glass in this case
                if (eyesDetected[0].Length == 0) continue;
                //draw the face detected in the 0th (gray) channel with blue color
                frame.Draw(f.rect, new Bgr(Color.Blue), 2);
                foreach (MCvAvgComp ey in eyesDetected[0])
                {
                    if (ey.neighbors > 100)
                    {
                        Rectangle eyeRect = ey.rect;
                        eyeRect.Offset(f.rect.X, f.rect.Y);
                        frame.Draw(eyeRect, new Bgr(Color.Red), 2);
                    }
                }
            }
            //display the image
            box.Image = frame;
        }

WPF OpenFileDialog

Ref:http://www.c-sharpcorner.com/UploadFile/raj1979/236/
1. The OpenFileDialog can't be work in WPF application.
    Ref: http://msdn.microsoft.com/zh-tw/library/system.windows.controls.openfiledialog(v=vs.95).aspx
    It seems to work in silverlight application.
2. Get the OpenFileDialog from Microsoft.Win32 and the Openfile method has to be changed.
    xaml parts was the same as msdn example while coding can be changed as follows
    private void bOpenFileDialog_Click(object sender, RoutedEventArgs e)
        {
            // Create an instance of the open file dialog box.
            // 3 Employ Win32 component            //OpenFileDialog openFileDialog1 = new OpenFileDialog();
            Microsoft.Win32.OpenFileDialog openFileDialog1 = new Microsoft.Win32.OpenFileDialog();

            // Set filter options and filter index.
            openFileDialog1.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
            openFileDialog1.FilterIndex = 1;
            openFileDialog1.Multiselect = true;
            // Call the ShowDialog method to show the dialog box.
            bool? userClickedOK = openFileDialog1.ShowDialog();
            // Process input if the user clicked OK.
            if (userClickedOK == true)
            {
                // Open the selected file to read.
                // 4 Change the OpenRead method
                // System.IO.Stream fileStream = openFileDialog1.File.OpenRead();
                System.IO.Stream fileStream = openFileDialog1.OpenFile();

                using (System.IO.StreamReader reader = new System.IO.StreamReader(fileStream))
                {
                    // Read the first line from the file and write it the textbox.
                    tbResults.Text = reader.ReadLine();
                }
                fileStream.Close();
            }
        }
5.

2011年5月21日 星期六

SQL Azure - 2

1. Rebuild SQL Azure Account. (tried too many times in the wrong password and typo second mail address)
2. Follow the Ex3-BuildingSQLAzureApp steps.
    a. Create a database as HolTestDB
    b. Employ SQL 2008 management Studio to implement tables
        copy AdventureWorks2008LT_Azure.sql to excute

    c. Add connection string
 <add name="AdventureWorksLTConnectionString" connectionString="Server=tcp:ydxpy7fu4v.database.windows.net,1433;Initial Catalog=HoLTestDB;Persist Security Info=True;
User ID = xx@ydxpy7fu4v Password = yyyyyy  ;Trusted_Connection=False;Encrypt=True;" providerName="System.Data.SqlClient" />


    d.Create Service Package Only
    e. Create a new host and upload the published package.
3. Test Results
   

2011年5月18日 星期三

C# 2008 Excel 連線

1. 主動台模式
2. Execl 檔案 d:\test1.xls
3. 第一列為欄位名稱,請用文字(否則會被更改)
4. 程式碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
namespace CSConsoleExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            OleDbDataAdapter cmd;
            DataSet ds = new DataSet();
            //String fileNameString = this.MapPath();
            //fileNameString += "\\" + fileNameTextBox.Text;
            OleDbConnection cn = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; data source=" + @"D:\test1.xls" + ";Extended Properties=Excel 8.0;");
            // Select the data from Sheet1 of the workbook.
            string SQL = "select * from [工作表1$]";
            cmd = new OleDbDataAdapter(SQL, cn);
            cn.Open();
            cmd.Fill(ds, "test0");
            cn.Close();
            Console.WriteLine(ds.Tables[0].Columns[0].Caption);
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                Console.WriteLine(ds.Tables[0].Rows[i].ItemArray[0]);
            }
        }
    }
}

VB 2008 Excel 連線

1. 主動台模式
2. Execl 檔案 d:\test1.xls
3. 第一列為欄位名稱,請用文字(否則會被更改)
4. 程式碼:
Imports System.Data
Imports System.Data.OleDb
Module Module1
    Sub Main()
        'OleDbDataAdapter cmd;
        Dim cmd As OleDbDataAdapter
        Dim ds As DataSet = New DataSet()
        'String fileNameString = this.MapPath();
        'fileNameString += "\\" + fileNameTextBox.Text;
        Dim cn As OleDbConnection = New OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; data source=" & "D:\test1.xls" & ";Extended Properties=Excel 8.0;")
        'Select the data from Sheet1 of the workbook.
        Dim SQL As String = "select * from [工作表1$]"
        cmd = New OleDbDataAdapter(SQL, cn)
        cn.Open()
        cmd.Fill(ds, "test0")
        cn.Close()
        Console.WriteLine(ds.Tables(0).Columns(0).Caption)
        For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
            Console.WriteLine(ds.Tables(0).Rows(i).ItemArray(0))
        Next
    End Sub
End Module

2011年5月10日 星期二

SpaceInvader作業-2

1. WindowForm 整合(執行DxStudio 的 Visual Studio ToolBox 選項)

2. WindowForm 工具箱增加Player選項

3. 加入修改後之SpaceInvader

4. 分別建立由表單應用程式執行script函數(shoot, addBigInvader)與讀、寫參數的按鈕事件:
        private void button1_Click(object sender, EventArgs e)
        {
            axDXStudioPlayer1.Send("scenes.scene_1.script.shoot()");
        }
        private void button2_Click(object sender, EventArgs e)
        {
            axDXStudioPlayer1.Send("scenes.scene_1.script.addBigInvader()");
        }
        private void button3_Click(object sender, EventArgs e)
        {
            string cam = "";
            axDXStudioPlayer1.GetPropertyAsString("layers.layer_1.camera", out cam);
            if (cam == "camera_1")
                axDXStudioPlayer1.Send("layers.layer_1.camera = 'camera_2'");
            else
                axDXStudioPlayer1.Send("layers.layer_1.camera = 'camera_1'");
        }

SpaceInvader作業

改變鍵盤事件
function doKeys()
// 改變高度,讓入侵者打不到, 或改為3D模式
if( keys.l && playerMoveEnable )   
 {
    objects.Player_1.pos.z += playerMoveSpeed;
 }
    if( keys.k && playerMoveEnable )   
 {
    objects.Player_1.pos.z -= playerMoveSpeed;
 }
// 增加 y方向移動
   if( keys.up && playerMoveEnable )   
 {
    objects.Player_1.pos.y += playerMoveSpeed;
 }
   if( keys.down && playerMoveEnable )   
 {
    objects.Player_1.pos.y -= playerMoveSpeed;
 }
// 改a,d 為 left, right 鍵
 if( keys.right && playerMoveEnable )   
 {
    objects.Player_1.pos.x += playerMoveSpeed;
  if( objects.Player_1.pos.x > 15 )objects.Player_1.pos.x = 15;
 }
 if( keys.left && playerMoveEnable )   
 {
  objects.Player_1.pos.x -= playerMoveSpeed;
  if( objects.Player_1.pos.x < 0 )objects.Player_1.pos.x = 0;
 }

2011年5月8日 星期日

SAP 跨網段設定(內定以SAP-SERVER名稱連線驗證,校內跨網段需增加IP連線驗證)

1.      伺服器右下方開啟SAP B1 Service Manager
2.      (2.5)開啟設定對話窗
3.      開啟安全設定(Configure Security)對話窗
4.      變更密碼對話窗(Change Site Password)
5.      選擇Sever Database Credentials
6.      選擇MSSQL_2008 (系統為SQL 2008)
7.      增加DB Server (除原來SAP-SERVER外,再加入IP)

SQL azure

1. 註冊 (登入 windows.azure.com, 登入 sql.azure.com)

2. 防火牆設定(本機端IP)
3. SQL 2008 R2 Management Studio 設定
4. Insert table 需加入 clustered Index

5. VS2010 連線測試OK

2011年5月2日 星期一

Azure Ex3 Test OK

1. Storage account: Ref: Deploying Windows Azure Services.docx
1-1 Step-By-Step Walkthrough (1-34)
1-2 Test OK
 1-3 刪除 Hosted Service (受限使用數目)

2. Ex3 Ref:Introduction to Windows Azure.docx
2-1. Change connection string
2-2 Upload Service
2-3 Test OK