卡西卡的小寶庫
寶庫寶庫寶庫

解決DateTime.Parse無法處理email日期和RSS日期

Widnwos Live Writer SDK & Plugins

單元測試xUnit

其它

 

C#產生動畫GIF

Posted In: , , . By 卡西卡

CodeProject: NGif, Animated GIF Encoder for .NET

優點:影像品質佳
缺點:速度較慢
Photobucket
Gif.Components.AnimatedGifEncoder e = new Gif.Components.AnimatedGifEncoder();
e.Start(@"c:\test.gif");
e.SetDelay(500);
//-1:no repeat,0:always repeat
e.SetRepeat(0);
for (int i = 0 ; i < 12; i++ )
{
    e.AddFrame( Image.FromFile( string.Format(@"F:\Downloads\map({0}).png", i) ) );
} // for
e.Finish();

HOWTO: create an animated GIF using .Net (C#) - Rick van den Bosch - Blog
優點:速度快,檔案小
缺點:影像品質較差,Microsoft GIF Animator及Adobe ImageReady CS2判定格式錯誤無法開啟(但IE和FF正常)。
Photobucket

 

其它資料:

 

Google Map API (6) 搜尋

Posted In: . By 卡西卡

關鍵:GClientGeocoder, getLocations
展示:http://klcintw.googlepages.com/google-map-GClientGeocoder.htm

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Google Maps (台灣)</title>
    <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key="
      type="text/javascript" for="http://klcintw.googlepages.com"></script>
   1:  
   2:     <script type="text/javascript">
   3:     //<![CDATA[
   4: var map = null;
   5: var geocoder = null;
   6: function load() {
   7:     // 檢查瀏覽器是否可使用 Google Map API
   8:     if ( GBrowserIsCompatible() ) {
   9:         map = new GMap2(document.getElementById("map"));
  10:         geocoder = new GClientGeocoder();
  11:         
  12:         // 設定地圖中心點
  13:         map.setCenter(new GLatLng(25.036772,121.520269), 14);
  14:     } // if
  15: }
  16:  
  17: // showLocation() is called when you click on the Search button
  18: // in the form.  It geocodes the address entered into the form
  19: // and adds a marker to the map at that location.
  20: function showLocation() {
  21:     var address = document.forms[0].q.value;
  22:     geocoder.getLocations(address, addAddressToMap);
  23: }
  24:     
  25: // addAddressToMap() is called when the geocoder returns an
  26: // answer.  It adds a marker to the map with an open info window
  27: // showing the nicely formatted version of the address and the country code.
  28: function addAddressToMap(response) {
  29:     map.clearOverlays();
  30:     if (!response || response.Status.code != 200) {
  31:         alert("查無資料!\n Sorry, we were unable to geocode that address");
  32:     } // if
  33:     else {
  34:         place = response.Placemark[0];
  35:         point = new GLatLng(place.Point.coordinates[1],
  36:                             place.Point.coordinates[0]);
  37:         marker = new GMarker(point);
  38:         map.addOverlay(marker);
  39:         marker.openInfoWindowHtml(place.address + '<br>' +
  40:           '<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode);
  41:     } // else
  42: }
  43:     
  44: // findLocation() is used to enter the sample addresses into the form.
  45: function findLocation(address) {
  46:     document.forms[0].q.value = address;
  47:     showLocation();
  48: }     
  49:     //]]>
  50:   
</script>
  </head>
  <body onload="load()" onunload="GUnload()">
  <h1>GClientGeocoder</h1>
    <form action="#" onsubmit="showLocation(); return false;">
      <p>
        <b>地址:</b>
        <input type="text" name="q" value="古亭國小" class="address_input" size="40" />
        <input type="submit" name="find" value="Search" />
      </p>
    </form>  
    <div id="map" style="width:500px; height:350px"></div>
    <ul>
    <li><a href="javascript:findLocation('台北市羅斯福路三段201號');">古亭國小(以地址尋找)</a></li>
    <li><a href="javascript:findLocation('古亭國小');">古亭國小(以名稱尋找)</a></li>
    </ul>
  </body>
</html>

snap026

 

  • 一般組態
    web.config
    <?xml version="1.0"?>
    <configuration>
      <appSettings file="out.config">
        <add key="in_string" value="IN"/>
      </appSettings>
    </configuration>

    out.config
    <?xml version="1.0" encoding="utf-8"?>
    <appSettings>
      <add key="out_string" value="out" />
    </appSettings>

    讀取組態:
    System.Configuration.ConfigurationManager.AppSettings["in_string"]
    System.Configuration.ConfigurationManager.AppSettings["out_string"]
  • 連線組態

    讀取組態:
    System.Configuration.ConfigurationManager.ConnectionStrings["default"].ConnectionString
    內部
    <?xml version="1.0"?>
    <configuration>
      <connectionStrings
        <add name="default" connectionString="Data Source=localhost;Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.SqlClient"/>
      </connectionStrings>
    </configuration>

    外部
    <!-- web.config -->
    <?xml version="1.0"?>
    <configuration>
      <connectionStrings configSource="conn.config" />
    </configuration>

    <!-- conn.config -->
    <connectionStrings>
      <add name="default" connectionString ="data=out;uid=;pid=;"/>
    </connectionStrings>

ASP.NET 1.1 是用 System.Configuration.ConfigurationSettings.AppSettings["default"]

 

Customers.aspx
=AJAX, 向web service請求資料。
[script]
function displayCustomers(result) {
$get("customers").innerHTML = result;
}
[script]

[body]
<asp:ScriptManager ID="ScriptManager1" runat="server" >
<Services>
<asp:ServiceReference Path="~/CustomerService.asmx" />
</Services>
</asp:ScriptManager>

Enter Country: <input id="Country" type="text" />
<a href="javascript:CustomerService.GetCustomersByCountry($get('Country').value, displayCustomers)">Show Customers</a>
<div id="customers"></div>
[/body]

CustomerService.cs
=這個AJAX用的web service是宣告 System.Web.Script.Services.ScriptService
using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class CustomerService : System.Web.Services.WebService {

[WebMethod]
public string GetCustomersByCountry(string country)
{
NorthwindTableAdapters.CustomersTableAdapter customersAdapter = new NorthwindTableAdapters.CustomersTableAdapter();
Northwind.CustomersDataTable customers = customersAdapter.GetCustomersByCountry(country);

if (customers.Rows.Count > 0)
return ViewManager.RenderView("~/App_Views/Customers.ascx", customers);
else
return ViewManager.RenderView("~/App_Views/NoCustomers.ascx", null);
}
}

Customers.ascx.cs
=View
using System;

public partial class App_Views_Customers : System.Web.UI.UserControl
{
public object Data;

protected void Page_Load(object sender, EventArgs e)
{
Repeater1.DataSource = Data;
Repeater1.DataBind();
}
}

ViewManager.cs
=Controller
using System;
using System.Web;
using System.Web.UI;
using System.IO;
using System.Reflection;

public class ViewManager
{
public static string RenderView(string path)
{
return RenderView(path, null);
}

public static string RenderView(string path, object data)
{
Page pageHolder = new Page();
UserControl viewControl = (UserControl) pageHolder.LoadControl(path);

if (data != null)
{
Type viewControlType = viewControl.GetType();
FieldInfo field = viewControlType.GetField("Data");

if (field != null)
{
field.SetValue(viewControl, data);
}
else
{
throw new Exception("View file: " + path + " does not have a public Data property");
}
}

pageHolder.Controls.Add(viewControl);

StringWriter output = new StringWriter();
HttpContext.Current.Server.Execute(pageHolder, output, false);

return output.ToString();
}
}
 


ASP.NET 1.1 只能用在.aspx上
StringWriter output = new StringWriter();
HttpContext.Current.Server.Execute("~/ajax.aspx", output);
return output.ToString();

參考資料:

 

Google Map API (5) AJAX

Posted In: , . By 卡西卡

參考資料:

 

GTileLayer:自己提供地圖圖檔在GMap上呈現。

重點在覆寫getTileUrl提供圖檔url。
b_tileLayers[0].getTileUrl = function(tile, zoom) {
  return "http://140.109.174.55/googlemap/stereo/"+zoom+
    '/'+tile.x+'/IMG_'+tile.x + '_' + tile.y + '_'+zoom+".jpg";
}

實例:

 

snap022

參考資料:

 

[筆記]Google Map API (2)

Posted In: . By 卡西卡

  • 處理地圖移動事件[]
    // 移動地圖後在中心點顯示座標
    GEvent.addListener(map, "moveend",
      function() { 
        var center = map.getCenter();
        map.openInfoWindow(map.getCenter(),document.createTextNode(center.toString()));
      }
    );

    // 縮放地圖後顯示前後級別
    GEvent.addListener(map, "zoomend",
      function(oldLevel,newLevel) { 
        document.getElementById("out").innerHTML = "oldLevel="+oldLevel+" , newLevel="+newLevel;
      }
    );
    // 顯示滑鼠點到的座標   
    GEvent.addListener(map, "click",
      function(overlay,latlng) {
        document.getElementById("log").value = latlng.toString();
      }
    );
  • 取得目前地圖的可視範圍,隨機加入10個標籤,並畫線[GLatLngBounds, GPolyline, ] 
    var bounds = map.getBounds();
    var southWest = bounds.getSouthWest(); // 返回矩形西南角的點
    var northEast = bounds.getNorthEast(); // 返回矩形東北角的點
    var lngSpan = northEast.lng() - southWest.lng();
    var latSpan = northEast.lat() - southWest.lat();
    var points = [];
    for (var i = 0; i < 10; i++){
        var point = new GLatLng(
            southWest.lat() + latSpan * Math.random(),
            southWest.lng() + lngSpan * Math.random());
        points.push(point);
        map.addOverlay(new GMarker(point));
    } // for
    // 排序
    points.sort(function(p1, p2) { return p1.lng() - p2.lng();});
    map.addOverlay(new GPolyline(points));

    snap021
  • 多邊形並著色[GPolygon, ]
    // 地圖 (400x400)
    map.setCenter(new GLatLng(25.02837276205344, 121.48509979248047), 12);
    var points = [];
    points.push(new GLatLng(25.030000,121.490556)); // 萬華
    points.push(new GLatLng(25.035556,121.424722)); // 新莊
    points.push(new GLatLng(25.063611,121.518056)); // 中山
    points.push(new GLatLng(24.978889,121.529167)); // 新店
    points.push(new GLatLng(25.013611,121.466667)); // 板橋
    points.push(new GLatLng(25.030000,121.490556)); // 萬華(封閉)
    map.addOverlay(new GPolygon(points,'#FF0000',3,0.5,'#ffff00',0.5));

    snap020

 

[JavaScript]Closure

Posted In: . By 卡西卡

Closure:閉包, 閉鎖空間, 封絕

  • 看起來有點像是“巨集”的,可以產生(return)新的函式。
// 打折
function Discount(percent) {
    return function(price) { return price * percent / 100.0; }
}

var VIP_Pay      = Discount(60); // 貴賓6 折
var Member_Pay   = Discount(80); // 會員8 折
var Consumer_Pay = Discount(95); // 門市95折
var dvd_price = 500;
print("DVD定價 "+dvd_price);
print("貴賓特惠價 "+VIP_Pay(dvd_price));
print("會員優待價 "+Member_Pay(dvd_price));
print("門市售價 "+Consumer_Pay(dvd_price));
/* 結果
DVD定價 500
貴賓特惠價 300
會員優待價 400
門市售價 475
*/

 

var i = 0; 
var funcSet = []; 
function run_funcSet() { 
    for (var j=0, func=funcSet[j] ; func ; func=funcSet[++j] ) { 
        func(); 
    } // for

print('Pure anonymous function'); 
for ( i=0 ; i<3 ; i++ ) { 
    funcSet[i] = function() {print(i);} 
} // for
run_funcSet(); 
print('Closure'); 
for ( i=0 ; i<3 ; i++ ) { 
    funcSet[i] = (
        function(i) {
            return function(){print(i);} 
        }
// function
    )(i); 
} // for
run_funcSet(); 
/* 結果
Pure anonymous function
3
3
3
Closure
0
1
2
*/

 

參考資料:

 

Google Map API (1)

Posted In: . By 卡西卡

Google 地圖

  1. 申請 Google Maps API Key
    網址:Sign Up for the Google Maps API
  2. 網頁編碼要用 UTF-8
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
  3. 基本程式 [GMap2]
  4. 增加功能:
    • 滑鼠滾輪拉近拉遠
      map.enableScrollWheelZoom();
    • 地圖大小、移動控制項
      map.addControl(new GLargeMapControl());
      map.addControl(new GSmallMapControl());
    • 地圖型態控制項(地圖、衛星、混合地圖、地形)
      map.addControl(new GMapTypeControl());
      map.addMapType(G_PHYSICAL_MAP); //增加地形圖 (參考:GMapType.Constants)
      map.setMapType(G_NORMAL_MAP); //設定預設地圖型態
    • 地圖型態控制項(下拉式)
      map.addControl(new GMenuMapTypeControl());
    • 鳥瞰圖
      map.addControl(new GOverviewMapControl());
    • 比例尺
      map.addControl(new GScaleControl());
  5. 在地圖上插上標籤 [GLatLng, GMarker, ]
    // 中正紀念堂
    var pos = new GLatLng(25.036772,121.520269);
    var mark = new GMarker(pos);
    map.addOverlay(mark);
  6. 插上自訂標籤 [GIcon, GMarkerOptions, GSize, GPoint, ]
    // 自訂標籤
    var icon=new GIcon();
    icon.image = "mark.gif";
    icon.iconSize = new GSize(16,16);
    icon.iconAnchor = new GPoint(8,8);
    icon.shadow = "mark.gif";
    icon.shadowSize = new GSize(1,1);
    icon.infoWindowAnchor = new GPoint(8, 8);
    icon.infoShadowAnchor = new GPoint(8, 8);
    // 中正紀念堂
    var pos = new GLatLng(25.036772,121.520269);
    var mark = new GMarker(pos, {icon:icon});
    map.addOverlay(mark);
  7. 點擊標籤顯示訊息
    // 處理mark的click事件
    GEvent.addListener(mark, "click", function() {mark.openInfoWindowHtml('中正紀念堂<br>可用HTML'); });
  8. 程式移動地圖
    // 5秒後移至台北火車站
    window.setTimeout(function() {
      map.panTo(new GLatLng(25.048708,121.516128));
    }, 5000);
     

參考資料:

 

[未完成]SQL CE筆記

Posted In: , . By 卡西卡

  • SqlCE3 的 SqlCeParameter 有BUG,NVarChar長度超過255都會被截掉。
    if (size <= 255)
      return new SqlCeParameter(name, SqlDbType.NVarChar, size);
    else
      return new SqlCeParameter(name, SqlDbType.NVarChar);

    據說
    • binary 和 varbinary 只能到 510
    • SqlCE 3.5以後才有解決。
    參考
     
  • CREATE TABLE 的語法中只能有一個欄位指定為 PRIMARY KEY
    若要指定多個欄位是PK必須使用ALTER ...
    "ALTER TABLE [" + TABLE_NAME + "] ADD CONSTRAINT [PK_" + TABLE_NAME + @"] PRIMARY KEY (
    SITE_PIDENT,PARAM_CODE,HOURLY_DATE )"
  • 讓ASP.NET可以用SqlCE必須加上
    AppDomain.CurrentDomain.SetData("SQLServerCompactEditionUnderWebHosting", true)
  • 不支援 TRUNCATE TABLE

其它參考:

 

SQL Server Compact Edition, SQL Server Mobile

 

Gestures:滑鼠(觸控筆)手勢,用動作來執行命令。

原文網址|摘要:

筆記:

  1. 要先安裝 OpenNETCF Smart Device Framework ( 2.2 Community Edition )
  2. 如果要套用到自己的程式碼
    1. 引用using vbAccelerator.Components.Win32;
      using OpenNETCF.Windows.Forms;
    2. 修改 Main() Application2.Run(new Form1()); // OpenNETCF.Windows.Forms.Application2
    3. form的建構式,InitializeComponent()之後加上 MouseGestureFilter mgf = new MouseGestureFilter();
      Application2.AddMessageFilter(mgf);
      mgf.MouseGesture+=new MouseGestureEventHandler(mgf_MouseGesture);
    4. 加上 mgf_MouseGesture private void mgf_MouseGesture(object sender, MouseGestureEventArgs args) {...}
  3. 可以在DataGrid上使用,但第一個MOUSE_DOWN的事件也會被datagrid收到,CurrentCell會改變。

    Screen02

  4. 雖然可以辨識手勢,但還做不到像TouchFLO的效果。
  5. 若將 args.AcceptGesture = true; 則所有事件都會被吞掉,不會向下傳到其它元件。
  6. 修改過的source[Box.net]

 

另一個Gestures相關的文章:CodeProject: Optimizing Screen Area using Mouse Gestures.

 

Detecting Internet Explorer More Effectively
http://msdn2.microsoft.com/en-us/library/ms537509.aspx
Understanding User-Agent Strings
http://msdn2.microsoft.com/en-us/library/ms537503(VS.85).aspx
About Conditional Comments
http://msdn2.microsoft.com/en-us/library/ms537512(VS.85).aspx

 

怎麼使"<div>"顯示到dropdownlist或listbox 的前面?
在div裡加iframe:
<div>
<iframe src="javascript:false" style="Z-INDEX:-1; FILTER:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0); LEFT:0px; VISIBILITY:inherit; WIDTH:158px; POSITION:absolute; TOP:0px; HEIGHT:110px">
</iframe>
</div>

 

問題:DateTime.Today.ToString("yyyy/MM/dd") 的結果一定是"2006/03/05"嗎?

OS: Windows Mobile 6 Professional (ASUS P750)

在「開始\設定\系統\區域設定」中,「中文(台灣的)」的「日期」日曆類型有三種,其中有一個「臺灣曆(中文)」會讓ToString吐出民國年,"97/03/05"!

不正確的日期字串導致不預期的錯誤啊……

Screen23
臺灣曆(中文)
Screen21
97/03/05
Screen19
西曆(英文)
Screen18
2008/03/05

DateTime.Parse 也有相同的情況。