遙遠的呼喚(zt)

Standard

或許這是很多人都有的故事經驗,抬頭遙望天空的繁星,夏日明亮的銀河是一條通往仙境的道路,聽說天有九重,總是有著美麗的憧憬,那裡住著聖人、佛和神仙,還有美麗的亭台樓閣與怡人的風景,消遙自在、詩書琴棋畫,無憂無慮的生活著。
 
當每個嬰兒來到這個世上,父母總是賜給他的名字,爾後不斷的呼喚,引導他認識新的事務,『識神』發達了,也因此逐漸淡忘並疏遠了來自遙遠的呼喚,『元神』逐漸削弱了,這就是存在於地球表面空間的人類。
 
『元神』是世人連通元始生身父母的臍帶,無形能量的臍帶,有朝一日必須透過這一條臍帶回到另一個存在。即使活在現世也必須透過這一條臍帶,才能獲得『般若大智慧』。世人散生娑婆世界,有了『識神』就生出了貪瞋痴的慾望,忘卻了回家的路徑,因此,耶穌教有『天父』之說,一貫道有『無極姥姆』之說,道教有『一炁化三清』之說,無非警示世人透過『元神』找到回家的路。

道教告訴大家現有的宇宙是由一炁化三清而來:
一化無形天尊即玉清元始天尊:由混洞太無元之青氣,化生為天寶君,又稱元始天尊。居清微天玉清境,故稱玉清。祂是掌管天庭的。
二化無始天尊即上清靈寶天尊:由赤混太無元玄黃之氣,化生靈寶君,又稱靈寶天尊,居禹餘天上清境,故稱上清。祂是掌管地界的。
三化梵形天尊即太清道德天尊:由冥寂玄通元玄日之氣,化生神寶君,又稱道德天尊,即太上老君,居大赤天太清境,故稱太清。祂是掌管人界的。
 
倘若按照道教的說法,無疑的天可能有三重空間。但是,自從人類發明火箭和太空船以後,發現月亮上面沒有住著嫦娥,佛教的西方極樂世界也不見了,因為地球只是太空中運轉的圓球。美麗的憧憬開始蒙上一層解不開的陰影。
 
對於這個世界,一般我們知道有長、寬、高三度空間,再加上時間,總共是四度空間。哈佛大學教授麗莎藍道爾說:「我認為(地球上)存在五度空間,等其他的次元,只是它們隱藏得很好,所以我們看不到而已。」
 
有人說:時間不變的固定為一次元、三次元空間就是所謂三度空間。假使我們以生活於其間的三次元空間為一重宇宙的空間,九次元空間分成三個三度空間,就有三重宇宙的空間。我們所知道的空間只有三度,那麼九度空間要怎麼樣來想像呢?有人認為我們的空間以外,還有平行空間存在。倘若把九度空間其中的三度當成一個軸,九度空間就成為三個軸。然而時間呢?因為宇宙中,時間不可能在這個空間與另外一個空間不同,否則有時候,從這個空間到另一個空間,再回來的話,變成時光倒流,這個不大合理,因此時間不會各自分段,所以把時間當成事件前後的同一共通性的計量標準。超弦理論的十次元時空的宇宙架構,可以看成三重的三次元空間和共用的一次元時間,合稱為三重宇宙的時空架構。如果以這種三重宇宙的時空架構,來探討一些目前科學上沒有辦法解釋的問題,就容易的多。當然這種觀點也只是世人一廂情願的看法。
 
有了三重宇宙時空架構的話,我們所看到的這個宇宙,只是整個宇宙的三分之一的空間而已,另外還有三分之二的空間看不到。
 
關於空間的概念,比方來說:一度空間的人類碰到前方的障礙只能後退或停止不前,因為他的世界是直線;二度空間的人類碰到障礙則知道繞道而行,因為他有面的概念;三度空間人類則會爬上那個障礙走過去,因為他有高度的概念;四度空間人類我猜會選擇回到或跨越到沒有那個障礙阻擋在前面的時間。那麼另外的幾度空間呢?
 
地球人類大都是以自己所見為信任的準則,人類不能避免習慣以直線的長、寬、高三度空間為想法,去思索另一次元的時空,這絕對患了一個很大的錯誤!宇宙之間的星球都以圓滾方式、以中軸傾斜角度自轉,以橢圓軌道作公轉,這就是拋物線方式、螺旋方式的前進方式。不但如此,整個宇宙也在向南前進中。易經的地風升卦說:『升,元亨,用見大人,勿恤,南征吉。』儘管他人並不一定做如此解釋。當然人們仍會不斷的思索探究神秘的高層異次元空間。
 
再說,愛因斯坦的質能方程式說明:物質就是能量。物理學家已經證明,我們這個世界上所有的固體都是由旋轉的粒子組成的,包括核子、中子、質子和外層的電子。這些粒子有著不同的振動頻率,粒子的振動使我們的世界表現成目前的樣子。我們人身的細胞也是如此結構。科學家已經測量過,人在不同的體格和精神狀態下身體的振動頻率,結果讓人大開眼界。
 
比如說,邪念會導致最低的頻率;當人想著下流的邪念,人體就在削弱自己。漸高依次是惡念、冷漠、痛悔、害怕與焦慮、渴求、發火和怨恨、傲慢,這些全都對人體有害。但『信任』是中性的,信任有益於人身。再往上的頻率依次是溫和、樂觀、寬容、理智和理解、關愛和尊敬、高興和安詳、平靜和喜悅,開悟為最高最快的頻率。
 
有人進一步的研究顯示,特瑞莎修女(1910-1997,獲1997年諾貝爾和平獎)的時候,當特瑞莎修女走進屋子裏的一瞬間,在場所有人的心中都充滿了幸福,她的出現使人們幾乎想不起任何雜念和怨恨,此時特瑞莎修女具有很高很快頻率。最高頻被稱為是神的意志或精神,這是絕對力量的頻率,甚或更高。傳說耶穌在村子裏的出現使圍上來的人們心裏除了耶穌什麼都沒有。善念的高頻率振動是否就是通往異次元時空的路徑?因為他們最終成為了『神』。
 
又有科學界研究太陽散發出來的微中子,科學家提出或許微中子是外星文明的通訊工具,因為星際通訊需要穿越遙遠的距離而不受干擾,且須具方向性,而微中子可以穿透所有物質星球,甚至穿透越數光年厚的鉛而不受阻擋,照樣穿透。此外,微中子偵測器的偵測能量帶極寬,或許是外星文明通訊的最好選擇,然而這也只是猜測。
 
我們以三重宇宙的觀念來看,倘若將微中子看成可以貫穿三重宇宙的每個空間,那麼則從太陽輻射出來的微中子,當然可以平均散發於全部宇宙的每個空間,而輻射到我們這一重宇宙的微中子,當然也只有三分之一而已,其餘三分之二散發於另外二重宇宙的空間。科學家已作了多次的實驗,發現地球實際接收到的微中子只接收到三分之一,其餘三分之二的太陽微中子不曉得那裡去?這個問題成為粒子天文領域上的一個大秘密,已困惱了四分之一世紀。
 
因為我們的地球只是在這三度空間裏,另外還有二個三度空間,即另外有二重宇宙,與我們同時存在;換句話說,任何一點的座標數有九個,其中三個座標是我們所知道的三度空間,其他六個座標是在另外的空間裏,目前我們沒有辦法去探求。
 
又有醫學界研究許多頻死經驗的人,一致的結論是「人死了以後 ,他的靈魂會飄過一個漆黑的隧道,到達一個光明的世界 。」
 
他們提出的看法,人死後的靈魂可能由現實的宇宙,穿出人類的空間,進入另一重宇宙的空間,那裡有無形的光明世界,就是在我所講的三重宇宙中,和我們不同的其中一重而已,將來我們也要到那個地方去,那裏才是真正的歸宿。
 
人類應該『享受直覺、相信科學』,識神賦予人類的謀生的機能,在世也需要具有精靈敏捷的頭腦,才能圓滿地處理世務,才能提升生活的品質;但也不能忽略元神的作用,元神不但賦予人類智慧,也能賦予人類產生靈感,進而感通宇宙的訊息,甚至是靈魂通往高層異次元時空的路徑。那遙遠的路徑,都是人類對外感官無從察覺的極微小的蜷曲的方向。活生生的人體的機制是非常完整的,人體以絕對性的機制配合著宇宙運行機制,只是人類在世大都只運用一半,就是『識神』,另外的一半必須關閉『識神』然後才能開啟『元神』的運作,這就是和宇宙合體運作的法訣。
 
禪門道派的法脈源自『崑崙山』屬於崑崙道脈,開傳始祖號為雲磐,居住崑崙山清靜宮玄金殿,剛入門時居於好奇,翻遍地理和典籍,從西藏到新疆、青海整條崑崙山脈,詳細閱讀和崑崙相關的風景、湖泊、廟宇、仙蹤典故,總是希望有朝一日能參訪謁祖,並體會一下仙山的靈氣。即使無法達成願望,做做白日夢也算給自己來些安慰。
 
世間事一切隨緣而生,經歷幾翻考驗,當萬緣復歸靜寂,透過某個微細的縫隙,跨越蜷曲的路徑,崑崙實在是一處極其美麗祥和的國度,崑崙其實是在高層異次元時空的其他的地方,是宗教的源頭,也是智慧的泉源,過去也曾由那裡傳出其他門派,也曾有西藏的喇嘛、印度的神秘家去過,並被報導出來。宇宙瞬息萬變,世事無常,當初各門各派各宗各教祖師們慈悲的傳法,或許有著當時的時空背景的需要,而身為後輩的人們呢?是否能繼續順著那條無形能量的臍帶,解讀來自遙遠的訊息,庇蔭人群趨吉避凶,繼承各祖師慈悲的關懷呢?
 
根據所知,人類居住的太陽系正在靠近宇宙中的一條光子帶,穿越光子帶我們會從三度空間進入高度異次元空間;伴隨發生的巨大變動,包括整個太陽系的電磁場以至人類自身的細胞、身體及意識層次的改變。光子帶中含有密集及高震動力的光子,所以產生的震動力非常強,物質本來是由光分子合組而成的,一旦被其影響,光子會改變人體的結構,我們的震動力將會瞬間被提升,身體變的較透明及輕盈,意識等級也將會被提升,不過不到程度的生命體將難以承受,原因和身上的頻率有關。
 
不但人類身上的頻率受影響,地球內部的磁場也在改變,這些改變在在影響人類的健康,有影響人類生活的環境,世界衛生組織的資料說,氣候暖化與變遷已造成每年至少十五萬人因瘧疾、腹瀉、營養不良及漲水傷害而死亡,這只是變遷的一部分,還有更多潛在的危機,這其中半數將會發生在亞太地區。
 
看得到的,在氣候暖化的影響之下,瘧疾帶原蚊已開始遷徙,出現在過去不曾出現的地區,如朝鮮和巴布亞新幾內亞的山區;至於登革熱,雖然未有證據指向亞洲的高病例與氣候暖化有直接關聯,但氣溫的升高及失常的降雨及產生的寒害已被證實扮演一定的角色。此外,亞洲巨型城市如加爾各答及馬尼拉的數以千萬計居民,將受到河流及沿海水患的威脅,南太平洋島嶼國家則將面臨海平面上升、土石流、頻繁的颱風及水荒等災害。

Deep clone an object in .NET

Standard

There are two types of object cloning; deep and shallow.

A shallow clone creates a new instance of the same type as the original object, with all its value-typed fields copied. However, the reference type fields still point to the original objects; and so the “new” object and the original reference to the same object. On the other hand, a deep clone of an object contains a full copy of everything directly or indirectly referenced by the object – and so you get a “true” copy.

One of the easiest ways to deep-copy an object is to serialize the object into memory and de-serialize it again – although this does require the object graph to be serializable. Here’s a handy code snippet to do this:

public static object CloneObject(object obj)
{
    using (MemoryStream memStream = new MemoryStream())
    {
        BinaryFormatter binaryFormatter = new BinaryFormatter(null, 
             new StreamingContext(StreamingContextStates.Clone));
        binaryFormatter.Serialize(memStream, obj);
        memStream.Seek(0, SeekOrigin.Begin);
        return binaryFormatter.Deserialize(memStream);
    }
}

You could then implement the ICloneable interface on your object like so:

public class MyObject  : ICloneable {
    public object Clone()
    {
        return ObjectUtility.CloneObject(this);
    }
    ...
}

VBScript-数组排序

Standard

Sub ArraySort(aArrayToSort, sOrder)
‘This script is provided under the Creative Commons license located
‘at http://creativecommons.org/licenses/by-nc/2.5/ . It may not
‘be used for commercial purposes with out the expressed written consent
‘of NateRice.com
‘This Sub will sort the array passed as aArrayToSort
For i = UBound(aArrayToSort) – 1 To 0 Step -1
For j = 0 To i
If aArrayToSort(j) < aArrayToSort(j+1) And sOrder = “desc” Then
sTempStr = aArrayToSort(j+1)
aArrayToSort(j+1) = aArrayToSort(j)
aArrayToSort(j) = sTempStr
ElseIf aArrayToSort(j) > aArrayToSort(j+1) And sOrder = “asc” Then
sTempStr = aArrayToSort(j+1)
aArrayToSort(j+1) = aArrayToSort(j)
aArrayToSort(j) = sTempStr
End If
Next
Next
End Sub

Sub DoubleArraySort(aArray1ToSort, aArray2ToSort, sOrder)
‘This script is provided under the Creative Commons license located
‘at http://creativecommons.org/licenses/by-nc/2.5/ . It may not
‘be used for commercial purposes with out the expressed written consent
‘of NateRice.com
‘This Sub will sort the array passed as aArray1ToSort,
‘the values in aArray2ToSort, will not be sorted, but
‘will be reordered in the same relational order as
‘aArray1ToSort
For i = UBound(aArray1ToSort) – 1 To 0 Step -1
For j = 0 To i
If aArray1ToSort(j) > aArray1ToSort(j+1) And sOrder = “desc” Then
sTempStr = aArray1ToSort(j+1)
aArray1ToSort(j+1) = aArray1ToSort(j)
aArray1ToSort(j) = sTempStr

sTempStr = aArray2ToSort(j+1)
aArray2ToSort(j+1) = aArray2ToSort(j)
aArray2ToSort(j) = sTempStr
ElseIf aArray1ToSort(j) < aArray1ToSort(j+1) And sOrder = “asc” Then
sTempStr = aArray1ToSort(j+1)
aArray1ToSort(j+1) = aArray1ToSort(j)
aArray1ToSort(j) = sTempStr

sTempStr = aArray2ToSort(j+1)
aArray2ToSort(j+1) = aArray2ToSort(j)
aArray2ToSort(j) = sTempStr
End If
Next
Next
End Sub

Debugging client JavaScript in VS 2005

Standard

Client Java Script is one of the most important things in web development but not the best and easiest to develop. Building of bigger and more complicated scripts, especially using DOM model or form field values can cause a lot of frustration and head pain. Moreover, JavaScript debugging is not easy and obvious as should be. But there is a hope.

One of less known features of Visual Studio 2005 is Script Explorer, hidden in Debug menu where appears only when the debugger is running. This great tool allows easily debug JavaScripts.

Before start, we should ensure that client script debugging is not disabled in IE as it is by default. Suitable options are located on Advanced tab of Internet Options where both script debugging checkboxes should be unchecked.

We can come back to Script Explorer. As it was written before, it appears only while the debugger is working. So after starting project we can go do Debug->Windows where should be Script Explorer. Sometimes, don’t know why, it doesn’t so in this case we have to find it manually. Staying in debug mode right click on tool bar and go into Customize. Then select Debug in Categories on the left side of window and find Script Explorer on the right. Just drag it to Debugging toolbar.

After opening Script Explorer panel we will se the tree of active JavaScripts. At the first level are scripts that are imported from external sources or embedded in the page. There are also auto-generated scripts like postback scripts as well. By double-clicking on the selected script it will open in the main window.

At this moment, we can debug it in well known way using breakpoints, steps, Watch and QuickWatch, just like in the server side, including context variable browsing.

Breakpoints can also be set up in external *.js files before project will be loaded. Then, after loading project, the breakpoint will be activated by debugger. Note, that it is only possible to *.js files not for scripts embedded in pages. These scripts are available for debugging only after loading page.

RAW FTP Commands Collection

Standard

可以用来自己写FTP Client。测试命名的方法:以window 自带的FTP命令为例:

命令行行下执行FTP,连接入FTP server。

然后通过Quote来执行RAW命令

 

C:UsersNolanShang>ftp 127.0.0.1
Connected to 127.0.0.1.
220-FileZilla Server version 0.9.37 beta
220-written by Tim Kosse (Tim.Kosse@gmx.de)
220 Please visit http://sourceforge.net/projects/filezilla/
User (127.0.0.1:(none)): nolan
331 Password required for nolan
Password:
230 Logged on
ftp> quote feat
211-Features:
MDTM
REST STREAM
SIZE
MLST type*;size*;modify*;
MLSD
UTF8
CLNT
MFMT
211 End
ftp>

Common Commands

  • ABOR – abort a file transfer
  • CWD – change working directory
  • DELE – delete a remote file
  • LIST – list remote files
  • MDTM – return the modification time of a file
  • MKD – make a remote directory
  • NLST – name list of remote directory
  • PASS – send password
  • PASV – enter passive mode
  • PORT – open a data port
  • PWD – print working directory
  • QUIT – terminate the connection
  • RETR – retrieve a remote file
  • RMD – remove a remote directory
  • RNFR – rename from
  • RNTO – rename to
  • SITE – site-specific commands
  • SIZE – return the size of a file
  • STOR – store a file on the remote host
  • TYPE – set transfer type
  • USER – send username

Uncommon Commands

  • ACCT* – send account information
  • APPE – append to a remote file
  • CDUP – CWD to the parent of the current directory
  • HELP – return help on using the server
  • MODE – set transfer mode
  • NOOP – do nothing
  • REIN* – reinitialize the connection
  • STAT – return server status
  • STOU – store a file uniquely
  • STRU – set file transfer structure
  • SYST – return system type

Descriptions

ABOR
Syntax: ABOR
Aborts a file transfer currently in progress.

ACCT*
Syntax: ACCT account-info
This command is used to send account information on systems that require it. Typically sent after a PASS command.

ALLO
Syntax: ALLO size [R max-record-size]
Allocates sufficient storage space to receive a file. If the maximum size of a record also needs to be known, that is sent as a second numeric parameter following a space, the capital letter “R”, and another space.

APPE
Syntax: APPE remote-filename
Append data to the end of a file on the remote host. If the file does not already exist, it is created. This command must be preceded by a PORT or PASV command so that the server knows where to receive data from.

CDUP
Syntax: CDUP
Makes the parent of the current directory be the current directory.

CWD
Syntax: CWD remote-directory
Makes the given directory be the current directory on the remote host.

DELE
Syntax: DELE remote-filename
Deletes the given file on the remote host.

HELP
Syntax: HELP [command]
If a command is given, returns help on that command; otherwise, returns general help for the FTP server (usually a list of supported commands).

LIST
Syntax: LIST [remote-filespec]
If remote-filespec refers to a file, sends information about that file. If remote-filespec refers to a directory, sends information about each file in that directory. remote-filespec defaults to the current directory. This command must be preceded by a PORT or PASVcommand.

MDTM
Syntax: MDTM remote-filename
Returns the last-modified time of the given file on the remote host in the format “YYYYMMDDhhmmss”: YYYY is the four-digit year, MM is the month from 01 to 12, DD is the day of the month from 01 to 31, hh is the hour from 00 to 23, mm is the minute from 00 to 59, and ss is the second from 00 to 59.

MKD
Syntax: MKD remote-directory
Creates the named directory on the remote host.

MODE
Syntax: MODE mode-character

Sets the transfer mode to one of:

  • S – Stream
  • B – Block
  • C – Compressed

The default mode is Stream.

NLST
Syntax: NLST [remote-directory]
Returns a list of filenames in the given directory (defaulting to the current directory), with no other information. Must be preceded by a PORT or PASV command.

NOOP
Syntax: NOOP
Does nothing except return a response.

PASS
Syntax: PASS password
After sending the USER command, send this command to complete the login process. (Note, however, that an ACCT command may have to be used on some systems.)

PASV
Syntax: PASV
Tells the server to enter “passive mode”. In passive mode, the server will wait for the client to establish a connection with it rather than attempting to connect to a client-specified port. The server will respond with the address of the port it is listening on, with a message like:
227 Entering Passive Mode (a1,a2,a3,a4,p1,p2)
where a1.a2.a3.a4 is the IP address and p1*256+p2 is the port number.

PORT
Syntax: PORT a1,a2,a3,a4,p1,p2
Specifies the host and port to which the server should connect for the next file transfer. This is interpreted as IP address a1.a2.a3.a4, port p1*256+p2.

PWD
Syntax: PWD
Returns the name of the current directory on the remote host.

QUIT
Syntax: QUIT
Terminates the command connection.

REIN*
Syntax: REIN
Reinitializes the command connection – cancels the current user/password/account information. Should be followed by a USER command for another login.

REST
Syntax: REST position
Sets the point at which a file transfer should start; useful for resuming interrupted transfers. For nonstructured files, this is simply a decimal number. This command must immediately precede a data transfer command (RETR or STOR only); i.e. it must come after any PORT or PASV command.

RETR
Syntax: RETR remote-filename
Begins transmission of a file from the remote host. Must be preceded by either a PORT command or a PASV command to indicate where the server should send data.

RMD
Syntax: RMD remote-directory
Deletes the named directory on the remote host.

RNFR
Syntax: RNFR from-filename
Used when renaming a file. Use this command to specify the file to be renamed; follow it with an RNTO command to specify the new name for the file.

RNTO
Syntax: RNTO to-filename
Used when renaming a file. After sending an RNFR command to specify the file to rename, send this command to specify the new name for the file.

SITE*
Syntax: SITE site-specific-command
Executes a site-specific command.

SIZE
Syntax: SIZE remote-filename
Returns the size of the remote file as a decimal number.

STAT
Syntax: STAT [remote-filespec]
If invoked without parameters, returns general status information about the FTP server process. If a parameter is given, acts like the LIST command, except that data is sent over the control connection (no PORT or PASV command is required).

STOR
Syntax: STOR remote-filename
Begins transmission of a file to the remote site. Must be preceded by either a PORT command or a PASV command so the server knows where to accept data from.

STOU
Syntax: STOU
Begins transmission of a file to the remote site; the remote filename will be unique in the current directory. The response from the server will include the filename.

STRU
Syntax: STRU structure-character

Sets the file structure for transfer to one of:

  • F – File (no structure)
  • R – Record structure
  • P – Page structure

The default structure is File.

SYST
Syntax: SYST
Returns a word identifying the system, the word “Type:”, and the default transfer type (as would be set by the TYPE command). For example: UNIX Type: L8

TYPE
Syntax: TYPE type-character [second-type-character]

Sets the type of file to be transferred. type-character can be any of:

  • A – ASCII text
  • E – EBCDIC text
  • I – image (binary data)
  • L – local format

For A and E, the second-type-character specifies how the text should be interpreted. It can be:

  • N – Non-print (not destined for printing). This is the default if second-type-character is omitted.
  • T – Telnet format control (<CR>, <FF>, etc.)
  • C – ASA Carriage Control

For L, the second-type-character specifies the number of bits per byte on the local system, and may not be omitted.

USER
Syntax: USER username
Send this command to begin the login process. username should be a valid username on the system, or “anonymous” to initiate an anonymous login.

C# Call by Name

Standard

sing .NET reflection we can attempt to access properties and function solely with their name.

 

The System.Reflection namespace holds a variety of classes and functions that takes C# programming to another level.

we accessed the Location property of myObject. We can also do the same through reflection:

Type t = myObject.GetType();
PropertyInfo p = t.GetProperty("Location");
Point location = (Point)p.GetValue(myObject, null);

Of course, PropertyInfo is location under the System.Reflection namespace. Notice that the code becomes significantly more complicated and susceptible to mistakes. For example, in the first example, trying to access a property that does not exist would trigger a compiler error. On the other hand, the example with Reflection compiles just fine no matter what property we try to access. The error will come up during run-time.

 

et’s take showMessage from our example above. The function does not return a value and does not take parameters. To call it with .NET reflection it would be done something like so:

Type t = this.GetType();
MethodInfo method = t.GetMethod("showMessage");
method.Invoke(this, null);

A word of warning. If you get a null-object exception that means the method was not found. The method has to be public for it to be able to be invoked through reflection. Also obfuscating the C# application can potentially cause the name of the method to change, which will cause the code to fail. These are just things to keep in mind.

Now let’s try to invoke the multiply function from the example above, which takes parameters and returns a value. The code is not all that different:

Type t = this.GetType();
MethodInfo method = t.GetMethod("multiply");
int result = (int)method.Invoke(this, new object[] { 3, 4 });

 

 

C# Set DataGridView Selection

Standard

DataGridView

When data is added or searched in a DataGridView, it make it easier for the user to programmatically change the DataGridView selection.

Unfortunately, setting the selected item is not as easy as a ListBox for example. The reasons being that DataGridView’s usually handle larger amounts of data and they are often bound to data sources. Either way, it’s a 3 step process.

Set DataGridView Selection

Here’s how to set the active row of a DataGridView. The two example variables will be dataGrid, which is a DataGridView, andindex, which is the index of the row you want to select with C# code.

First is to scroll down the DataGridView so the row is visible in the screen:

dataGridView1.FirstDisplayedScrollingRowIndex = index;
dataGridView1.Refresh();

Then you must select the row so that binding sources update their Current item:

dataGridView1.CurrentCell = dataGrid.Rows[index].Cells[0];

Finally, you can visually select the row with C#:

dataGridView1.Rows[index].Selected = true;

Conclusion

The C# code above assumes that you are trying to select an entire DataGridView row. However it is simple to adjust if you just want to select a Cell. Otherwise the code will work to set the DataGridView selection.

 

Optimizing C# Application

Standard

Code optimization is an important aspect of writing an efficient C# application. The following tips will help you increase the speed and efficiency of your C# code and applications.

1. Knowing when to use StringBuilder

You must have heard before that a StringBuilder object is much faster at appending strings together than normal string types.

The thing is StringBuilder is faster mostly with big strings. This means if you have a loop that will add to a single string for many iterations then a StringBuilder class is definitely much faster than a string type.

However if you just want to append something to a string a single time then a StringBuilder class is overkill. A simple stringtype variable in this case improves on resources use and readability of the C# source code.

Simply choosing correctly between StringBuilder objects and string types you can optimize your code.

2. Comparing Non-Case-Sensitive Strings

In an application sometimes it is necessary to compare two string variables, ignoring the cases. The tempting and traditionally approach is to convert both strings to all lower case or all upper case and then compare them, like such:

str1.ToLower() == str2.ToLower()

However repetitively calling the function ToLower() is a bottleneck in performace. By instead using the built-in string.Compare()function you can increase the speed of your applications.

To check if two strings are equal ignoring case would look like this:

string.Compare(str1, str2, true) == 0 //Ignoring cases

The C# string.Compare function returns an integer that is equal to 0 when the two strings are equal.

3. Use string.Empty

This is not so much a performance improvement as it is a readability improvement, but it still counts as code optimization. Try to replace lines like:

if (str == "")

with:

if (str == string.Empty)

This is simply better programming practice and has no negative impact on performance.

Note, there is a popular practice that checking a string’s length to be 0 is faster than comparing it to an empty string. While that might have been true once it is no longer a significant performance improvement. Instead stick with string.Empty.

4. Replace ArrayList with List<>

ArrayList are useful when storing multiple types of objects within the same list. However if you are keeping the same type of variables in one ArrayList, you can gain a performance boost by using List<> objects instead.

Take the following ArrayList:

ArrayList intList = new ArrayList();
intList.add(10);
return (int)intList[0] + 20;

Notice it only contains intergers. Using the List<> class is a lot better. To convert it to a typed List, only the variable types need to be changed:

List<int> intList = new List<int>();
intList.add(10)
return intList[0] + 20;

There is no need to cast types with List<>. The performance increase can be especially significant with primitive data types like integers.

5. Use && and || operators

When building if statements, simply make sure to use the double-and notation (&&) and/or the double-or notation (||), (in Visual Basic they are AndAlso and OrElse).

If statements that use & and | must check every part of the statement and then apply the “and” or “or”. On the other hand, && and ||go thourgh the statements one at a time and stop as soon as the condition has either been met or not met.

Executing less code is always a performace benefit but it also can avoid run-time errors, consider the following C# code:

if (object1 != null && object1.runMethod())

If object1 is null, with the && operator, object1.runMethod()will not execute. If the && operator is replaced with &,object1.runMethod() will run even if object1 is already known to be null, causing an exception.

6. Smart Try-Catch

Try-Catch statements are meant to catch exceptions that are beyond the programmers control, such as connecting to the web or a device for example. Using a try statement to keep code “simple” instead of using if statements to avoid error-prone calls makes code incredibly slower. Restructure your source code to require less try statements.

7. Replace Divisions

C# is relatively slow when it comes to division operations. One alternative is to replace divisions with a multiplication-shift operation to further optimize C#. The article explains in detail how to make the conversion.

Conclusion

As you can see these are very simple C# code optimizations and yet they can have a powerful impact on the performance of your application. To test out the optimizations, try out the free Optimizing Utility.

Profiling

An important concept when it comes to increasing the speed and efficiency of you C# code, is code profiling. A good profiler can not only let you know about the speed bottlenecks in your applications, but it can also help you with memory management. The best .Net profiler is probably RedGates ANTS Profiler. They have a free trial at their homepage you can download before purchasing the full product.

 

A tip about ADO.NET

Standard

通过ADO.NET取得的DataTable,Dataset中DataColumn的MaxLength属性有时取不到想要的值,比如有个varchar类型的字段,长度应该是100,但是返回的确是-1。

当然可以通过其他方式取得表的Schame信息,但这样多了一步。

通过查资料发现这是微软的一个BUG。解决办法很简单,设置一下SqlDataAdapter的MissingSchemaAction属性:

string strQuery = "SELECT * FROM tbl_MyTable";
objConn = new SqlConnection(strConnString);
objConn.Open();
objCmd = new SqlCommand(strQuery, objConn);
objDA = new SqlDataAdapter(objCmd);
objDA.MissingSchemaAction = MissingSchemaAction.AddWithKey;
objDS = new DataSet();
int iCount = objDA.Fill(objDS);

Windows 7 No such interface supported 错误

Standard

今天Windows 自己系统更新,更新我重启系统,结果罢工,桌面上任何操作,如设置桌面,打开文件夹,打开控制面板等。都提示No such interface supported,无法进行操作。

用SFC没有效果,后来将系统的dll全部注册一下,就好了:

方法:

调出系统运行对话框:输入cmd,然后同时安装Ctrl+Shift,然后确认,则cmd以管理员身份运行:

接下来输入命令:

FOR /R C: %G IN (*.dll) DO "%systemroot%system32regsvr32.exe" /s "%G"

然后等待这个命令运行完毕,期间会弹出一些警告框,不用理他,因为有些DLL不是COM组件。

运行完重新启动系统,我的系统就正常了