星期四, 10月 28, 2010

[Silverlight][VB]透過VisualTreeHelper找出DependencyObject內之Object

Private Function GetVisualTreeObject(Of T)(ByVal obj As DependencyObject)
    Dim child As DependencyObject
    Dim count As Integer = VisualTreeHelper.GetChildrenCount(obj)
    For index = 0 To count - 1
        child = VisualTreeHelper.GetChild(obj, index)
        If child.GetType().Name = GetType(T).Name Then
            Return child
        End If
        child = GetVisualTreeObject(Of T)(child)
        If Not IsNothing(child) Then
            Return child
        End If
    Next
    Return Nothing
End Function

Private Function FindInternalObjectByName(Of T)(ByVal name As String, ByVal obj As DependencyObject)
    Dim child As DependencyObject
    Dim count As Integer = VisualTreeHelper.GetChildrenCount(obj)
    For index = 0 To count - 1
        child = VisualTreeHelper.GetChild(obj, index)
        If child.GetType().Name = GetType(T).Name Then
            Dim fe As FrameworkElement = child
            If fe.Name = name Then
                Return child
            End If
        End If
        child = GetVisualTreeObject(child)
        If Not IsNothing(child) Then
            Return child
        End If
    Next
    Return Nothing
End Function

[Silverlight][VB]將Grid的ColumnDefinition的width轉為DependencyProperty

ColumnWidth轉為DependencyProperty

Private Shared ReadOnly ColumnWidthProperty As DependencyProperty = DependencyProperty.Register("ColumnWidth", GetType(Double), GetType(MainPage), New Windows.PropertyMetadata(AddressOf ColumnWidthChanged))
Private Property ColumnWidth() As Double
Get
Return DirectCast(GetValue(ColumnWidthProperty), Double)
End Get
Set(ByVal value As Double)
SetValue(ColumnWidthProperty, value)
End Set
End Property

Private Shared Sub ColumnWidthChanged(ByVal d As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs) 'GridCol1 is a name of ColumnDefinition
DirectCast(d, MainPage).GridCol1.Width = New GridLength(DirectCast(e.NewValue, Double))
End Sub




星期二, 9月 07, 2010

[Silverlight] 將畫面上元件輸出為圖片

VB:

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Click
        Dim bitmap As WriteableBitmap = New WriteableBitmap(can, Nothing)

        If Not IsNothing(bitmap) Then
            Dim savedia As SaveFileDialog = New SaveFileDialog()
            savedia.Filter = "JPEG Files (*.jpeg)|*.jpeg"
            savedia.DefaultExt = ".jpeg"

            If savedia.ShowDialog() Then
                Using st As System.IO.Stream = savedia.OpenFile()
                    SaveToFile(bitmap, st)
                    MessageBox.Show("done")
                End Using
            End If
        End If

    End Sub

    Private Shared Sub SaveToFile(ByVal bitmap As WriteableBitmap, ByVal st As System.IO.Stream)
        Dim wid As Integer = bitmap.PixelWidth
        Dim hei As Integer = bitmap.PixelHeight
        Dim bands As Integer = 2
        Dim raster()(,) As Byte = New Byte(bands)(,) {}

        For index = 0 To bands
            raster(index) = New Byte(wid, hei) {}

        Next

        For row = 0 To hei - 1

            For col = 0 To wid - 1
                Dim pixel As Integer = bitmap.Pixels(wid * row + col)
                Dim tmp As Integer

                tmp = (pixel >> 16) Mod 256
                raster(0)(col, row) = (256 + tmp) Mod 256
                tmp = (pixel >> 8) Mod 256
                raster(1)(col, row) = (256 + tmp) Mod 256
                tmp = pixel Mod 256
                raster(2)(col, row) = (256 + tmp) Mod 256

            Next

        Next
        Dim model As ColorModel = New ColorModel() With {.colorspace = ColorSpace.RGB}
        Dim img As FluxJpeg.Core.Image = New FluxJpeg.Core.Image(model, raster)

        Using ms As System.IO.MemoryStream = New System.IO.MemoryStream
            Dim encoder As FluxJpeg.Core.Encoder.JpegEncoder = New FluxJpeg.Core.Encoder.JpegEncoder(img, 100, ms)
            encoder.Encode()
            ms.Seek(0, IO.SeekOrigin.Begin)
            Dim binary() As Byte = New Byte(ms.Length) {}
            Dim byteread = ms.Read(binary, 0, ms.Length)
            st.Write(binary, 0, binary.Length)
        End Using

    End Sub

C#:網路找就有了...差異較大的地方就是轉byte,VB CByte很蠢就是了...
此外要去抓fjCore dll才能使用

星期四, 9月 02, 2010

取得本機使用者登入ID

VB:

dim UserID = System.Security.Principal.WindowsIdentity.GetCurrent.Name.Split("\")(1)


C#:

string UserID = System.Security.Principal.WindowsIdentity.GetCurrent().Name.Split("\\")(1);

星期四, 8月 12, 2010

NET 擴充方法

參見

C#:

public static class ExtendTest
{
 public static int Test(this string str) //for u want type
  { // ...}
}


VB:

<Extension()> _
Public Sub Test(byval str as String) 'for u want type
  ' .....
End Sub

星期三, 6月 23, 2010

取得時區時間

這是取得中國時區時間,其它時間輸入其id即可取得

Dim d2 As DateTime = DateTime.UtcNow.AddHours(TimeZoneInfo.FindSystemTimeZoneById("China Standard Time").BaseUtcOffset.Hours)


秀出所有的timezone資訊

Dim str As String = ""
Dim currentTime As DateTime
For Each tzi In TimeZoneInfo.GetSystemTimeZones
currentTime = DateTime.UtcNow.AddHours(tzi.BaseUtcOffset.Hours)
str = str & String.Format("ID:{0}, StandardName:{1}, Time:{2}", tzi.Id, tzi.StandardName, currentTime) & System.Environment.NewLine
Next

星期四, 4月 08, 2010

取得屬性名稱集合


Dim data As New MyObject
dim list as new List(of string)
For Each da In data.GetType().GetProperties().ToList()
list.Add(da.Name)
Next

透過屬性名稱 取得值


using System.Reflection;

object obj;
Type t = obj.GetType();
PropertyInfo pi = t.GetProperty("YourPropertyName");
object YourValue = pi.GetValue(obj,null)

星期二, 4月 06, 2010

Silverlight 使用imagebrush 填圖


Dim imgbrush As ImageBrush = New ImageBrush() With {.ImageSource = New BitmapImage(New Uri("Images/SomeImage.png", UriKind.Relative))}

星期二, 3月 30, 2010

Save & Read File (txt)


string dir = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); //系統路徑
string path = dir + "\\autoPlan.ini";
if (File.Exists(path))
{
StreamReader sr = new StreamReader(File.OpenRead(path));
while ((data = sr.ReadLine()) != "")
{
//.....
}
}

============================================================

StreamWriter sw = new StreamWriter(File.OpenWrite(path));
sw.WriteLine("Something");
sw.Close();

星期四, 3月 18, 2010

silverlight Clipboard


Imports System.Windows.Browser

Public Class SLClipboard
Private Shared data As String = ""
Public Shared Function GetText() As String
Dim clipboarddata As ScriptObject = HtmlPage.Window.GetProperty("clipboardData")

If IsNothing(clipboarddata) Then
MessageBox.Show("Sorry, this functionality is only avaliable in Internet Explorer.")
Else
data = clipboarddata.Invoke("getData", "text")
End If
Return data
End Function

Public Shared Sub SetText(ByVal txt As String)
data = txt
Dim clipboarddata As ScriptObject = HtmlPage.Window.GetProperty("clipboardData")
If IsNothing(clipboarddata) Then
MessageBox.Show("Sorry, this functionality is only avaliable in Internet Explorer.")
Else
clipboarddata.Invoke("setData", "text", data)
End If
End Sub

End Class

=====
參...
http://weblogs.asp.net/manishdalal/archive/2008/11/12/cross-browser-copy-and-paste-in-datagrid-with-excel-support-part-1.aspx

星期五, 3月 12, 2010

VB函數用法

VB函數說明 / VB函數用法

絕對值 / Abs(number)

傳回陣列範本 / Array(arglist)

算字元的ASCII碼 / Asc( string)

轉Boolean型態值 / CBool( expression )

轉Byte型態值 / CByte( expression )

轉Currency型態值 / CCur (expression )

轉Date型態的值 / CDate (date )

轉 Double 型態的值 / CDbl (expression )

轉ASCII碼表示的字元 / Chr (charcode)

轉為整數型態 / CInt(expression)

轉為長整數型態 / Clng (expression )

傳回物件範本 / CreateObject (class)

轉為單精度型態 / CSng (expression)

轉為字串型態 / CStr (expression )

傳回目前系統時間 / Date

傳回更改的時間 / DateAdd (interval, number, date)

傳回兩日期的間隔 / DateDiff (interval,date1,date2)

傳回某時間的部分值 / DatePart (interval,date)

轉換某時間Date型態 / DateSerial(year, month, day)

傳回陣列內的字串位置 / Filter (InputStrings, Value)

傳回Date 型態的值 / DateValue(date)

傳回1~31的日期數字 / Day(date)

最大整數值 / Int (number )

無條件捨去小數 / Fix (number)

傳回表示式型式 / FormatCurrency(Expression)

傳回日期或時間表示式 / FormatDateTime (Date)

傳回數字的表示式 / FormatNumber(Expressiom)

傳回百分比的表示式 / FormatPercent(Expression)

取回檔案內的物件 / GetObject([pathname][,class])

轉為16進位 / Hex(number)

傳回時間的時數 / Hour(time)

顯示可供輸入的對話窗 / inputBox(prompt,......)

傳回搜尋字串的位置 / InStr(string,searchstr)

從尾端搜尋字串位置 / InstrRev(string,searchstr)

判定變數是否為陣列 / IsArray(varname)

判定是否為日期表示式 / IsDate(expression)

判定變數內是否有內容 / IsEmpty(expression)

判定是否為NULL值 / IsNull(expression)

判定是否為數字值 / IsNumeric(expression)

傳回一個圖片物件 / LoadPicture(picturename)

判定是否為一個變數 / IsObject(expression)

字串加入陣列內 / Join(list[,delimiter])

轉為小寫字串 / LCase(string)

字串取左邊長度 / Left(string,ength)

傳回字串長度 / Len(string|varname)

傳回自然對數值 / Log(number)

去除字串的左邊空白 / LTrim(string)

去除字串的右邊空白 / RTrim(string)

去除字串的左右邊空白 / Trim(string)

傳回指定位置的字串 / Mid(string,start[,length])

傳回時間的分鐘 / Minute(time)

傳回日期的月份 / Month(date)

傳回月份字串 / MonthName(month[,abbreviate)

顯示一個訊息窗 / MsgBox(prompt,...)

傳回系統日期與時間/ Now

轉為八進位數字 / Oct(number)

取代部份字串 / Replace(string,find,replacewith)

字串取右邊長度 / Right(string,ength)

傳回一個隨機數字 / Rnd[(number)]

指定字串轉成陣列 / Split(expression,...)

傳回使用的Script語言 / ScriptEngine

傳回時間的秒數 / Second(time)

判斷數字的正負符號 / Sgn(number)

傳回弧度數字的Sin值 / Sin(number)

產生空白字元字串 / Space(number)

算數值的二次方根植 / Sqr(number)

比較兩字串 / StuComp(string1,string2[,compare])

反過來排列字串 / StrReverse(string)

產生重複字元字串 / String(number,character)

傳回目前的系統時間 / Time

傳回時間Date型態 / TimeSerial(hour,minute,second)

傳回含時間的Date型態 / TimeValue(time)

傳回變數的資料型態 / TypeName(varname)

從尾端傳回陣列小索引 / UBound(anayname)

轉為大寫字元 / UCase(string)

傳回代表變數資料型態的數字 / VarType(varname)

傳回日期是禮拜幾? / Weekday(date,[firstdayofweek])

傳回日期內的年數值 / Year(date)

====
網路上隨便搜尋就有了

星期四, 3月 11, 2010

十六進位表示法

不同電腦系統、編程語言對於16進制數值有不同的表示方式:

* Ada用所基於的「數字引證」把16進位數包起來,例如「16#5A3#」。(註:Ada對整數和實數都可以使用從1到16中任何一個做為其基數。)
* VHDL中使用字首 X,例如,X"10",對應的二進位碼為:"00010000".
* C語言、Python語言及其他相近的語言使用字首「0x」,例如「0x5A3」。開頭的「0」令解析器更易辨認數,而「x」則代表十六進位(就如「O」代表八進位)。在「0x」中的「x」可以大寫或小寫
* 在VB中,使用字首「&H」來表示
* 在HTML,十六進位字元可以用「x」,例如֣和֣效果應該無異
* 某些版本的BASIC語言會採用「&H」詞頭,例如:「&H5A3」。
* Pascal和某些匯編器用字尾「h」來辨別16進位的數(若該數以字母起首,在前面會增加一個「0」)例如「0A3Ch」、「5A3h」
* 其他匯編器(AT&T、Motorola)和某些BASIC的版本使用字首「$」,例如「$5A3」
* 亦有用X'5A3'這類表示方式的,如PL/I

由於表示方式沒有單一、已協定的標準,所以以上的表示方式都有被使用,有時甚至在同一份論文上會出現幾個不同的表示方式。但因為各方式之間沒有太大的分歧,所以即使混合使用也沒有構成問題。

其中最常用(或常見)表示十六進位數值的方式是將 '0x' 加在數字前,或在數字後加上小字 16。例如 0x2BAD 和 2BAD16 都是表示十進位的11181(或1118110)。

在網頁設計上十六進制是很常用的。HTML和CSS使用十六進制的表示法來表示網頁上的特定顏色。使用 # 的符號來表示而非用個別的符號表示十六進制。24-bit 顏色可以用 #RRGGBB 的格式來表示,RR 是顏色中紅色成分的數值,GG 是顏色中綠色成分的數值,BB 顏色中藍色成分的數值。舉個例子, 紅色的陰影是十進制 238,9,63 可以編成 #EE093F。參見 網頁顏色模式.

在URL的特殊字元亦是用ASCII中的十六進位,每位元組都有百份比符號(%)在前,例如: 空格就表示為%20,而中文維基百科的首頁地址就是 http://zh.wikipedia.org/wiki/Wikipedia:%E9%A6%96%E9%A1%B5 (在一些現代的瀏覽器,如Firefox中,地址中十六進位編碼會被解碼成實際字元,所以在這些瀏覽器中中文維基百科的首頁地址顯示成 http://zh.wikipedia.org/wiki/Wikipedia:首頁 )

轉至Wiki

星期二, 3月 09, 2010

Silverlight Set Image


someImage = new New ImageBrush() With {.ImageSource = New BitmapImage(New Uri("folder/img.jpg", UriKind.Relative))}

星期二, 3月 02, 2010

GetURl

public class GetUrl
{
public static string GetAbsoluteUrl(string strRelativePath)
{
if (string.IsNullOrEmpty(strRelativePath))
return strRelativePath;

string strFullUrl;
if (strRelativePath.StartsWith("http:", StringComparison.OrdinalIgnoreCase)
|| strRelativePath.StartsWith("https:", StringComparison.OrdinalIgnoreCase)
|| strRelativePath.StartsWith("file:", StringComparison.OrdinalIgnoreCase)
)
{
// 已經是絕對路徑。
strFullUrl = strRelativePath;
}
else
{
// 是相對路徑,必須轉換成絕對路徑。
strFullUrl = System.Windows.Application.Current.Host.Source.AbsoluteUri;
if (strFullUrl.IndexOf("ClientBin") > 0)
strFullUrl = strFullUrl.Substring(0, strFullUrl.IndexOf("ClientBin")) + strRelativePath;
else
strFullUrl = strFullUrl.Substring(0, strFullUrl.LastIndexOf("/") + 1) + strRelativePath;
}

return strFullUrl;
}
}

===============================================
Public Class GetUrl
Public Shared Function GetAbsoluteUrl(ByVal strRelativePath As String) As String
Dim strFullUrl As String

If String.IsNullOrEmpty(strRelativePath) Then
Return strRelativePath
End If



If strRelativePath.StartsWith("http:", StringComparison.OrdinalIgnoreCase) _
Or strRelativePath.StartsWith("https:", StringComparison.OrdinalIgnoreCase) _
Or strRelativePath.StartsWith("file:", StringComparison.OrdinalIgnoreCase) Then
strFullUrl = strRelativePath
Else
strFullUrl = System.Windows.Application.Current.Host.Source.AbsoluteUri

If (strFullUrl.IndexOf("ClientBin") > 0) Then
strFullUrl = strFullUrl.Substring(0, strFullUrl.IndexOf("ClientBin")) + strRelativePath
Else
strFullUrl = strFullUrl.Substring(0, strFullUrl.LastIndexOf("/") + 1) + strRelativePath
End If
End If


Return strFullUrl
End Function
End Class

Lambda for VB

Dim checkName As Func(Of String, Boolean) = _
Function(x As String) _
If(x = "Cabernet Sauvignon", True, False)

星期五, 9月 19, 2008

自訂事件

public delegate void myEventHandle(object sender, myEventArgs e);
public event myEventHandle myEvent;

.
.
.

protected void onEvent(object sender, myEventArgs e)
{
if (myEvent!= null)
{
myEvent(sender, e);
}
}

星期三, 6月 04, 2008

以loop透過取代變數名稱設定值

Dictionary variables = new Dictionary();

foreach( string temp in words )
{
variables[ temp + "_buy" ] = "4";
}

星期四, 5月 15, 2008

畫透明背景範例

http://www.codeproject.com/KB/dotnet/transparent_controls_net.aspx

星期三, 5月 14, 2008

剪貼簿使用

string str = (string)Clipboard.GetData(DataFormats.StringFormat);

Clipboard.SetDataObject("test");