2011年11月12日 星期六

unicode space vs ascii space

1. A powershell process was actuated by a console mode and/or asp.net program. An example copied from web page was not work properly as the they said in the web page. It took me quite a long time to test since the unicode space can not be recognised.
2. The following figure is the example:

 

2011年11月1日 星期二

WindowsServerAppFabric (I)

1. Winddows ServerApplicationFabric 範例,別太在意Error Message
(2012-1-3 修訂 : 要在意error, 因為練習太多已建置WCF服務,所以可以執行
 問題1: 請以Administrators角色開啟,才有權限在wwwroot建置WCF服務
 問題2: 若已建置且檔案位置不同,須先刪除wwwroot的WCF)















2. 跟隨說明
2.1 重建

------ 已開始全部重建: 專案: SaleClient, 組態: Debug x86 ------
  SaleClient -> D:\ServerAppFabric\WindowsServerAppFabricSamples\WindowsServerAppFabricSamples\SampleApplication\CS\OrderApplication\SaleClient\bin\Debug\SaleClient.exe
========== 全部重建: 1 成功、0 失敗、 0 略過 ==========
2.2 IIS 應用程式集區 DefaultAppPool 設為.NET Framework 4.0 版
2.3 以檔案總管執行SalesClient.exe
3. 測試
3.1 改 24 in Monitor order 2
3.2 Place order
3.3 自動產生order
3.4 Copy Order ID
3.5 重新以Order ID 檢查。







2011年10月24日 星期一

Facebook WinForm API (4)

批次處理圖片下載
1. 結合API(2) API(3) 功能,將好友大頭貼批次下載如下:
Image im = null;
                        foreach (dynamic friend in result)
                        {
                            textBox1.Text +=   friend.last_name + friend.first_name +  ": Facebook username: " + friend.username + "\n\n";
                           
                            im = DownloadImageClass.DownloadImage(string.Format(friend.pic_square));
                            im.Save(friend.name + ".jpg");
                        }
2. Test OK!

Facebook WinForm API (3)

測試下載圖片 GraphApiAsyncExample();
1. Ref: http://www.digitalcoding.com/Code-Snippets/C-Sharp/C-Code-Snippet-Download-Image-from-URL.html
1.1 下載網頁圖片
2  用Ref1建立 Class DownloadImageClass, 製作DownloadImage類別方法。
3. 修改  GraphApiAsyncExample()
var fb = new FacebookClient(_accessToken);
            try
            {
                dynamic result = fb.Get("/me");
                var name = result.name;
                lnkName.Text = "Hi " + name;
                lnkName.LinkClicked += (o, e) => Process.Start(result.link);
                // available picture types: square (50x50), small (50xvariable height), large (about 200x variable height) (all size in pixels)
                // for more info visit http://developers.facebook.com/docs/reference/api
                picProfilePic.LoadAsync(string.Format("https://graph.facebook.com/{0}/picture?type={1}", result.id, "square"));
// ----------- 建置image 物件
// ----------- 下載網址圖片
// ----------- 另存圖檔 Test1.jpg
                Image im = null;
                im = DownloadImageClass.DownloadImage(string.Format("https://graph.facebook.com/{0}/picture?type={1}", result.id, "square"));
                im.Save("Test1.jpg");
4. 測試OK!

Facebook WinForm API (2)

1. There are three forms in this example:
1.1 Mainform (start program)
1.2 Browser in a form (login)
1.3 WinForm (Employ api communicate with Facebook server)
2. Test FqlAsyncSample() @  WinForm class
There are serveral testing methods in the constructor
            _accessToken = accessToken;
            InitializeComponent();
            GraphApiAsyncExample();
            LegacyRestApiAsyncExample();
            FqlAsyncSample();
            FqlMultiQueryAsyncSample();
            GraphApiBatchRequestAsyncSample();
            GraphApiExample();
3.  FqlAsyncSample();
 private void FqlAsyncSample()
        {
            var fb = new FacebookClient(_accessToken);
// 非同步語法             fb.QueryAsync(query); @ 最後一行,完成後執行此事件
            fb.GetCompleted +=
                (o, e) =>
                {
                    if (e.Error == null)
                    {
                        var result = (IList<object>)e.GetResultData();
                        var count = result.Count;
                        lblTotalFriends.Text = string.Format("You have {0} friend(s).", count);
                        foreach (dynamic friend in result)
                        {
// friend.屬性 由 SELECT 欄位名稱決定
                            textBox1.Text +=   friend.last_name + friend.first_name +  ": Facebook username: " + friend.username + "\n\n";
                        }
   
                    }
                    else
                    {
                        MessageBox.Show(e.Error.Message);
                    }
                };
            // query to get all the friends
            var query = string.Format("SELECT uid,pic_square, name, last_name, first_name  FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1={0})", "me()");
            fb.QueryAsync(query);
        }
4. 圖片 pic_square 為url
friend.pic_square
http://profile.ak.fbcdn.net/hprofile-ak-snc4/491XX_560998701_3563_q.jpg

2011年10月22日 星期六

圖形比對(Image matching)

1. Ref: http://briian.com/?p=7224
TinEye 可以用來作為圖形比對。
2. Ref: http://www.tineye.com/search/209759428e73f8572d44b91b861a40f4df7113b9/
提供線上比對tineye資料圖庫
example

3. 似乎有API可以運用。

2011年9月19日 星期一

ASUS TF101 Wiimote

1. ASUS TF101 安裝 WiimoteController 可以操作(取代Mouse)。 2. 觸控螢幕鍵盤失效,需停止WiimoteController, 觸控鍵盤功能可以恢復。

2011年8月30日 星期二

C# Linq (1)

Silverlight application 看來像要運用WCF連接資料庫,先試一下Linq to SQL
工作環境: Windows 7 (x86), VS2010, SQL 2008 R2
1. VS 2010 伺服器管理,連接資料庫
2. 主控台專案,加入新項目(資料 > Linq To SQL 類別) DataClass1.dbml
3. 拖取資料表(Table)進入DataClass1.dbml
4. 記得全部儲存。
5. 測試程式:
static void Main(string[] args)
{
DataClasses1DataContext db = new DataClasses1DataContext();
var ths = (
from us in db.teacher
select new { us.user, us.Email, us.education }).Take(2);
foreach (var t in ths)
{
Console.WriteLine(t.user +"," + t.Email + "," + t.education);
}

}
6.


2011年8月12日 星期五

Server 2008 x64 OleDB

1. 轉移ASP.NET網頁。
2. 系統Server 2008 x64, w/o Office
3. 網頁讀取 Access Database 錯誤 Microsoft.Jet.OLEDB.4.0 提供者並未登錄於本機電腦上。
4. IIS ASP.NET 啟用32位元應用。

Server 2008 IIS (ASP.NET 4.0 尚未在Web 伺服器上註冊)

1. 安裝Server 2008, ASP.NET 網頁無法啟動。
2. VS 2010 檢查顯示: ASP.NET 4.0 尚未在Web 伺服器上註冊
3. Cmd 模式:切換目錄
C:\>cd \WINDOWS\Microsoft.NET\Framework\v4.0.30319
4.註冊
C:\Windows\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis.exe /i
開始安裝 ASP.NET (4.0.30319)。
...............
完成安裝 ASP.NET (4.0.30319)。
5.


2011年7月11日 星期一

Google Map API (Flex) 練習1

1. Flex 4.5
2. Apply Google MAP API Key
3. Download Google Map API (Flash) SDK
4. Ref: http://code.google.com/intl/zh-TW/apis/maps/documentation/flash/basics.html
MapOptionsInit.html
5. 地圖中心置於HWC(25.081,121,396)
6. 開新專案
7. 加入Flash SDK
8. 加入範例程式(修改座標,mx:script 改為 fx:script:
>maps:Map xmlns:maps="com.google.maps.*"
id="map"
mapevent_mappreinitialize="onMapPreinitialize(event)"
width="100%" height="100%"
sensor="false"
key="ABQIAAAAAgF6Qq8S-..."/< >fx:Script< >![CDATA[
import com.google.maps.LatLng;
import com.google.maps.Map;
import com.google.maps.MapEvent;
import com.google.maps.MapType;
import com.google.maps.MapOptions;
private function onMapPreinitialize(event:Event):void {
var opts:MapOptions = new MapOptions();
opts.zoom = 15;
opts.center = new LatLng(25.081,121.396);
opts.mapType = MapType.NORMAL_MAP_TYPE;
this.map.setInitOptions(opts); } ]]< >/fx:Script< 9. 執行

Google Map API 練習1

1. 第三版以後,測試Google Map API,如果用量不大,沒有Key也可以用。
2. 參考範例 疊加層(polyline-simple.html)
http://code.google.com/intl/zh-TW/apis/maps/documentation/javascript/overlays.html
將地圖中心改為醒吾,放大倍率改為15,調整三角形尺寸。
3. 網站執行htm檔案(本機端直接以IE開啟亦可)
4. 測試步驟
4-1 以檢視原始檔方式開啟,全選貼上記事本。
4-2 修改css連結
原為
>link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
改為

4-3 改中心座標HWC (25.081, 121.396)
// var myLatLng = new google.maps.LatLng(24.886436490787712, -70.2685546875);
4-4 改zoom 5--> 15, mapTypeID => ROADMAP
4-5 依據中心點,改多邊形(三角形)座標
var triangleCoords = [
new google.maps.LatLng(25.086, 121.396),
new google.maps.LatLng(25.076, 121.391),
new google.maps.LatLng(25.076, 121.401),
new google.maps.LatLng(25.086, 121.396),
];
4-6 以utf-8格式存檔,上傳

5. 連結網址,可以檢視原始檔轉存。

2011年7月9日 星期六

以 .NET Framework 進行平行程式設計(1)

Ref:
1. http://msdn.microsoft.com/zh-tw/library/dd235608.aspx
2. http://www.cnblogs.com/tansm/archive/2010/03/29/TaskTest.html

.NET 4.0 提供平行處理程式庫,在 System.Threading.Tasks 命名空間下,有系列類別提供便捷的方法製作平行處理與非同步作業。主要類別為
System.Threading.Tasks.Task (表示可以等候和取消的非同步作業)
System.Threading.Tasks.Task(Of TResult) (屬於可以傳回值的工作)
Factory 類別提供靜態方法,這些方法可建立和啟動工作
System.Threading.Tasks.TaskScheduler 類別提供預設執行緒排程基礎結構。
Ref 2 提供不錯的Task測試範例
1. a,b,c,d 四個工作
2. c等待 a,b 完成,開始執行
3. d等待 a完成, 開始執行
4-1. Add using System.Threading.Tasks;
4-2 建立 TestAction類別
a. 建構元建立工作名稱與延遲時間
b. Do 方法輸出開始、等待延遲、輸出完畢
public class TestAction
{
public TestAction(string actionName, int p)
{
_actionName = actionName;
_p = p;
}

private int _p;
private string _actionName;
public void Do()
{
Console.WriteLine("開始執行" + _actionName);
System.Threading.Thread.Sleep(new TimeSpan(0, 0, _p));
Console.WriteLine("執行完畢" + _actionName);
}
}
4-3 測試主程式
static void Main(string[] args)
{
TaskFactory factory = new TaskFactory();
Task a = factory.StartNew((new TestAction("A", 2)).Do);
Task b = factory.StartNew((new TestAction("B", 5)).Do);
Task c = factory.ContinueWhenAll(new Task[] { a, b }, ((preTasks) => (new TestAction("C", 1)).Do()));
Task d = factory.ContinueWhenAll(new Task[] { a }, ((preTasks) => (new TestAction("D", 1)).Do()));
Console.WriteLine("俟A,B,C,D工作完畢(C執行完畢),輸入Enter結束程式");
Console.ReadLine();
}


5. 下載

2011年7月6日 星期三

emgu WPF 2

前篇用Timer來做映像擷取,略遜於此篇用DispatchInactive。
1. 加入image標籤
2. 加入參考: Emgu.CV, Emgu.CV.UI, Emgu.Util, System.Drawing
3. 加入 [DllImport("gdi32")]
private static extern int DeleteObject(IntPtr o);
public static BitmapSource ToBitmapSource(IImage image)
{ ... }
4. 加入 private void Window_Loaded(object sender, RoutedEventArgs e)
{
capture = new Capture();
this.Dispatcher.Hooks.DispatcherInactive += new EventHandler(Hooks_DispatcherInactive);
}
5. 加入事件方法
Image frame = capture.QueryFrame();
{
if (frame != null)
{
webcam.Source = ToBitmapSource(frame);
}
}
6. 結果
7. 下載

2011年6月30日 星期四

Microsoft azure - Google Map API, Skydrive pptx

1. Microsoft 還蠻夠意思,帳號到期還可以用一下。
2. 測試原有專案(queuecode)。
3. GuestBook_WebRole加入Webform2.aspx(Google Map API)

4. 再加入WebForm3.aspx 用iframe內置Skydrive公用屬性的pptx

2011年6月29日 星期三

Microsoft skydrive testing

突然間Office 365新聞很多,趕快來試試看Web Office
1. 登入windows Live
2. ppt 測試


3. Excel 測試


4. 網路硬碟測試(下載OK, 上傳有些問題?)
用 SkydriveSimpleViewer找出網路硬碟設定, e.g.
\\lkdpxx.docs.live.net\3bd9ec3d389212xx\
不同的id: lkdpxx 似乎都指向根目錄。


今天圖片上傳有問題,改天再傳圖。

2011年6月19日 星期日

Microsoft Kinect(第三課 SkeletonFrame)

Ref : SketetalViewer_Walkthrough.docx
PART 3—C# SkeletalViewer Sample
1. Open WPF Application
2. Add ref Microsoft.Research.Kinect
3. Add using Microsoft.Research.Kinect.Nui;
4. Copy parts of sample code as follows to test videostream function
4-1 Global variables
Runtime nui;
int totalFrames = 0;
int lastFrames = 0;
DateTime lastTime = DateTime.MaxValue;
const int RED_IDX = 2;
const int GREEN_IDX = 1;
const int BLUE_IDX = 0;
Dictionary<JointID, Brush> jointColors = new Dictionary<JointID, Brush>() { ...

4-2 Window_Loaded event method (Parts of them from example)
Key steps:
4-2-1 Create Runtime object
nui = new Runtime();
4-2-2 Initialize Runtime object
nui.Initialize(RuntimeOptions.UseDepthAndPlayerIndex | RuntimeOptions.UseSkeletalTracking | RuntimeOptions.UseColor);
4-2-3 Open VideoStream
nui.VideoStream.Open(ImageStreamType.Video, 2, ImageResolution.Resolution640x480, ImageType.Color);
4-2-4 Set SkeletonFrameReady event
nui.SkeletonFrameReady += new EventHandler<SkeletonFrameReadyEventArgs>(nui_SkeletonFrameReady);

4-3 Copy methods from example
4-3-1 getDisplayPosition
4-3-2 getBodySegment
4-3-3 nui_SkeletonFrameReady

4-4 Notes: Don't miss Width and Height settings in canvas.
<Canvas Name="skeleton" Width="300" Height="400" Margin="278,20,20,20" Background="Black" ClipToBounds="True" />

5 Download https://sites.google.com/site/csjoublogfiles/home/files/SDKSkeleton.zip

Microsoft Kinect(第二課 VideoStream)

Ref : SketetalViewer_Walkthrough.docx
PART 3—C# SkeletalViewer Sample
The C# SkeletalViewer application is installed in the following folder:
Users\Public\Documents\Microsoft Research KinectSDK Samples\NUI\SkeletalViewer\CS
The sample is implemented in the following files:
• App.xaml declares application-level resources.
• App.xaml.cs contains the code behind app.xaml.
• MainWindow.xaml declares the layout of the main application window.
• MainWindow.xaml.cs contains the code behind the main window, which implements NUI API initialization, processing and display.
• SkeletalViewer.ico defines the application icon that is used in title bar and task bar.
1. Open WPF Application
2. Add ref Microsoft.Research.Kinect
3. Add using Microsoft.Research.Kinect.Nui;
4. Copy parts of sample code as follows to test videostream function
4-1  Global variables
        Runtime nui;
        int totalFrames = 0;
        int lastFrames = 0;
        DateTime lastTime = DateTime.MaxValue;
        const int RED_IDX = 2;
        const int GREEN_IDX = 1;
        const int BLUE_IDX = 0;

4-2 Window_Loaded event method (Parts of them from example)
Key steps:
4-2-1 Create Runtime object
  nui = new Runtime();
4-2-2 Initialize Runtime object
  nui.Initialize(RuntimeOptions.UseDepthAndPlayerIndex | RuntimeOptions.UseSkeletalTracking | RuntimeOptions.UseColor);
4-2-3 Open VideoStream
 nui.VideoStream.Open(ImageStreamType.Video, 2, ImageResolution.Resolution640x480, ImageType.Color);
4-2-4 Set VideoFrameReady event
 nui.VideoFrameReady += new EventHandler<ImageFrameReadyEventArgs>(nui_VideoFrameReady); 

       
4-3 VideoFrameReady event method (Copy from sample)
  // 32-bit per pixel, RGBA image
            PlanarImage Image = e.ImageFrame.Image;
            im1.Source = BitmapSource.Create(
                Image.Width, Image.Height, 96, 96, PixelFormats.Bgr32, null, Image.Bits, Image.Width * Image.BytesPerPixel);
            ++totalFrames;
            DateTime cur = DateTime.Now;
            if (cur.Subtract(lastTime) > TimeSpan.FromSeconds(1))
            {
                int frameDiff = totalFrames - lastFrames;
                lastFrames = totalFrames;
                lastTime = cur;
                this.Title = frameDiff.ToString() + " fps";
            }
Notes: im1 is a image object set in xaml file
5 Download: https://sites.google.com/site/csjoublogfiles/home/files/KinectSDKEx1.zip

Microsoft Kinect for Windows SDK Beta from Microsoft Research(第一課)

Ref: http://research.microsoft.com/en-us/um/redmond/projects/kinectsdk/default.aspx
System: Windows 7 x86 + VS 2010
Kinect sensor
1. 安裝SDK含驅動程式。

2. 執行 Sample skeletal viewer
3. 辨識能力不錯(部分腳被遮蔽)

2011年6月8日 星期三

2011年6月6日 星期一

Facebook Winform API Test OK

1. Download Facebook C# SDK 5.0
1.1 SDK
1.2 Sample code

2. Create Facebook api to get ID
3. VS 2010 Open CSWinFormsAuthTool    fill app id in MainForm.cs
    //private string _appId = "{app id}";
    private string _appId = "2272280...";

4. Run App
5. Sample code   

2011年6月4日 星期六

Lesson 3 for Flex 4.5 (3D Rotating effect)

1. Open a Web project
2. Create assets folder and put into a picture file.
3. Copy cod
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
      xmlns:s="library://ns.adobe.com/flex/spark"
      xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
 <s:layout>
  <s:BasicLayout />
 </s:layout>

 <fx:Declarations>
  <s:Rotate3D id="rotate3DX"
     target="{image}"
     angleXFrom="0"
     angleXTo="360"
     duration="2000"
     autoCenterTransform="true" />

  <s:Rotate3D id="rotate3DY"
     target="{image}"
     angleYFrom="0"
     angleYTo="360"
     duration="2000"
     autoCenterTransform="true" />

  <s:Rotate3D id="rotate3DZ"
     target="{image}"
     angleZFrom="0"
     angleZTo="360"
     duration="2000"
     autoCenterTransform="true" />
 </fx:Declarations>

 <mx:ApplicationControlBar width="100%" cornerRadius="0">
  <s:Button id="buttonX"
      label="Rotate3D X-axis"
      click="rotate3DX.play();" />
  <s:Button id="buttonY"
      label="Rotate3D Y-axis"
      click="rotate3DY.play();" />
  <s:Button id="bButtonZ"
      label="Rotate3D Z-axis"
      click="rotate3DZ.play();" />
 </mx:ApplicationControlBar>
 <!--resizeMode="scale" -->
 <s:BitmapImage id="image"
       source="@Embed('assets/fx_appicon.jpg')"
       smooth="true"
       x="30"
       y="40"
       width="100"
       height="100" />

</s:Application>

4. Run project


5. Down load code

2011年6月3日 星期五

Lesson 2 for Flex 4.5 (Animation)

1. New Flex Web Project
2. Add animation instructions as follows:
<fx:Declarations>
  <!-- Place non-visual elements (e.g., services, value objects) here -->
  <!-- ref : http://seantheflashguy.com/flex/Flex3EffectsExample/srcview/index.html -->
  <mx:Sequence id="compEffect"  repeatCount="0"  repeatDelay="1500">
   <mx:Move xTo="200" />
   <mx:Move yTo="200" />
   <mx:Move xTo="100" />
   <mx:Move yTo="100" />
  </mx:Sequence>
 </fx:Declarations>
3. Add canvas
<mx:Canvas id="myCanvas"
      creationCompleteEffect="compEffect"
      x="100" y="100"
      width="100"
      height="100"
      backgroundColor="#0000ff"/>
4. Run the Project
5. Download code

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)