关于H1B美国报税一些注意事项(转载)

Standard

初到美国,报税是重要的一件事,也是麻烦的(对于我)。在网上找到一些中文的内容,转过来,以供参考。

——————————————(张哲瑞联合律师事务所 张大钦律师)——————————————————————–

很多在美国生活的外国人都曾存有一个疑问:我要不要向美国政府报税。 这个问题答案因人而异。 但总体上说,大部分外国人(包括F, M, J, H1B, L-1, O-1,TN等等),如果在美国境内有收入,都应该报税(filing tax returns)。 只不过,不同的报税身份,会有不同的报税义务,要求和方法。
每一年的个人所得税应在下一年的4月15号之前申报完毕。4月15号快到了, 张哲瑞律师事务所在这里提醒广大的移民要在截止日期前完成2008年的报税。如果您不能在2009年4月15号之前报清2008年的税,您可以向税务局(IRS)申请 两到四个月的宽限期。

人在社会, 有两样东西,你一生是逃不脱的: 一个是死亡,另一个是纳税。 粗略算一下,你会知道,您每天的劳动收入,有相当一部分其实是给了政府。你的薪酬,还没有挨着您口袋就给政府预先缴扣了。 到了口袋的部分,在流转的过程中层层盘剥,雁过拔毛。如果您买了房子,就得缴纳地税;开了车子,就得缴纳汽油税;每天到超市买东西,就得交销售税;存了点钱在银行里,就要交利息税;拿去投资,赚了钱,可能要交利得税。 一辈子攒了点钱不容易,想给子孙后代留着,还要交遗产税。 这样下来,一年十二个月,大概有二到五个月,人们是给政府义务打工去了。 当然,税收是取之于民,还之于民的。廉洁高效的政府,其税收相当部分应该是最终返还了人民。正所谓: 我为人人,人人为我。  然而,此口袋出,彼口袋入。人们会习惯地希望,我的口袋少出一点,别人的口袋少入一些。 因此, 一样简单不过的税收原理,(I-D)R – C = T , 到了每个人的帐本上,算法就不一样了。

这种算法的差异,跟每一个人的身份和状况有关。 在移民法上,在美国的外国人可以分为三种身份:移民 (immigrant),非移民 (non-immigrant)和未经登记的移民 (undocumented)。 在税法上,在美国的外国人只分为两类: 定居外国人(resident  alien)  和非定居外国人(non-resident alien)。 虽然税务局在界定外国人纳税义务时,有参照移民法上的一些定义,但是,切不可把移民法的定义和税法的定义混同起来。

根据美国税法,定居外国人(resident  alien)和美国公民的报税是类似的 —— 要就全球范围内的收入向美国政府报税。而非定居外国人(non-resident alien)则只需要就美国境内产生的收入报税。此外,resident  alien和non-resident alien的税项,税率,减免范围和征收方式也不一样。其中一个重大区别是:resident alien 要缴纳social security tax 和Medicaid 的, 而non-resident alien则不需要。 光这一项,就意味着7.65% 的赋税差别。当然,Resident 也有好处。 Resident 在收入抵扣(deduction)方面比non-resident 更优惠, 在享受公众设施(如大学学费)方面也更实惠。

一般地,绿卡持有人, 从I-485批准之日起,或者从持移民签证登陆美国之日起,肯定是税法意义上的 “resident” 了。 绿卡人士(永久居民)应该就全球范围内的收入向美国政府报税,这点是毫无疑问的。移民法上的永久居民(lawful permanent resident)一定是 税法意义上的定居外国人 (resident alien); 但是,税法上的resident 则并不一定是移民法上的lawful permanent resident。 譬如说, H1B 没有绿卡, 但是H1B有可能是 “resident ”。 叫很多人想不到的是, 一旦H1B 满足了“resident ”的要件或者自愿选择成为 “resident ”, 他们就应该向美国政府报告他们的全球收入了。

非绿卡外国人要成为“resident ”, 有两种途径,其一是满足“substantial presence test”.  另外一个途径是在报税时自愿选择成为 “resident ”.  后面的情况通常见于H1B的头一两年。由F-1转成H1B的那一年,前一段是F-1, 后一段是H1B, 报税是你可以按“dual status” 来报;在某种条件下,你也可以选择按 “resident” 来报。 另外, 如果夫妻一方是H1B, 要按 resident 来报税,那么另一方,不管是在F-1 还是H4, 都可以夫唱妇随地按照resident  来联合报税。

前一种途径,按substantial presence test程式来测试,如果过去三年内,您有183“天”或更多的时间身在美国,您应该按“resident ”报税。

测试程式如下:
• 本纳税年度内有31天置身美国,并且
• 本纳税年度和此前两年度,累计有183“天”在美国,“天”的算法是:
本年度内的1天算1天,去年的一天算1/3 天,前年的一天按1/6天算。

举例说, 张三,非绿卡人士,2000年第一次到美国,从2000到2003年,每年都在美国122天。 按照以上的程式测试, 张三在2000年应该是“non-resident”。 张三在2001年还是“non-resident”因为累计的天数是122+122×1/3=162.6. 但在2003年, 张三应该按 “resident” 报税因为累计天数达到183天。 (122+122×1/3+122×1/6=183)

这测试不适用于处于F, M, J身份下的学生,交换学者和他们的附属配偶。 因为美国的税法给了这几种人一些例外豁免(exemption). 通常地,F-1 学生在美国的头五年和J-1 访问学者的头两年会被视为“non-resident”。F, M, J 等非定居外国人(non-resident alien),通常只需要就美国境内的FDAP收入 (fixed or determinable annual or periodical gains, profits and income) 报税。FDAP 收入包括:薪资wage and compensation, 利息interest, 分红 di idends,租金 rents, and 版税royalties recei ed from US sources. 但炒股赚的钱和房屋买卖所获得的利得 (capital gain)有可能不包括在FDAP里。此外, ECI 收入 (Income of non-resident alien that is Effecti ely Connected with the conduct of a U.S. trade or business)也是要报税的。  需要提醒的是, 根据中国和美国的双边条约,在美国的F, M, J中国学生学者,其收入低于5000美元的部分,是可以根据条约免税的。

有人认为,凡是学校发的奖学金都是不用报税的,这是误解。Scholarship 和 Grant可能是FDAP收入, 有可能要报税。 但是,税法对奖学金在税率和抵扣有一些优惠规定。
寻找准确的答案,您可以访问税务局网站里的相关法律:http://www.irs.go /businesses/small/international/index.html

在模棱两可的状况下,是按“resident”还是按“non-resident”来报税更实惠呢? 答案因人而异。 但最重要的一条是:正确报税最实惠。 错误报税后果最严重。如果绿卡人士错误地按“non-resident”报了税,这可能导致失去永久居民的身份。如果一个在OPT阶段的学生选择了按“resident”来报税,他就要多缴纳社会保险金和医疗金。要知道,如果一个外国人(包括H1B)离开了美国,他给美国政府缴纳的社会保险金和医疗金是无法在退休时享受到的,而且也不可能向美国政府去索回。

移民局在很多问题上会审查申请人或受益人的税收记录。 譬如说, 在某些I-140移民申请,移民官要看雇主的报税和外国雇员的报税来确定雇主是否有足够的财政能力来支付外国雇员承诺的薪水。很多I-485调整身份的案子, 移民官要看经济担保人的报税来确定申请人是否有足够的经济来源来支持自己和家庭以不至于成为公众负担。虽然,移民局不大可能主动从税务局调取申请人的税收记录。 但, “Honesty is the best policy.”如果一个人因报税失误被罚款或被定罪,那么他的绿卡申请或入籍申请有可能受影响。

很多新移民在报税的问题上不够审慎,因小失大。这苦果, 连一些聪明杰出的美国公民也概莫能外。 君不见, 奥巴马提名的内阁官员,至少有四个栽在报税问题上, 最后不得不撤回了提名。就连当今叱咤风云的美国财政部长也险些在报税问题上葬送了美好前程。

在美国,报税是检验一个社会成员责任操守和诚信良知的试金石。 新移民追求美国梦想的同时,一定要记住,每一个梦想,都饱含着付出。 每一份权利,都意味着义务。

如果您决心要在美国这片土地上谋求发展的话,请从履行纳税的义务开始吧。 报税是一个多还少补的过程。 跟政府结帐,不一定总是你吃亏。 有些时候, Uncle Sam还要倒贴钱给你呢。

报税不是难事。很多大学社区有免费报税的服务。 你可以从邮局拿到表格,从移民局下载表格,或者从网上购买智能软件来报税。 此外,你也可以通过报税公司(如,TurboTax  和H&R Block )或专业人士来协助报税。  如果要长期在美国生活,对报税的知识多了解一些总归是有好处的。 

在报税表格方面,Resident 应和美国公民一样使用1040表, 1040A表 或1040EZ表。 Non-resident 应使用1040NR表或 1040NR-EZ表。 从谨慎的角度来看, F, M, J的学生学者,只要在美国有工作收入, 他们都应该要报税。 H1B, O-1 , L-1, TN等符合“substantial presence test”的外国人士有可能要就全球范围内的收入报税。

在此需要声明的是:我本人不是税务律师,上面的介绍只是围绕着移民话题展开的宽泛而谈。 如果有拿捏不准的地方, 你可以查阅税务局的FAQ. http://www.irs.go /faqs/index.html
复杂的状况,最好请教专业会计师,税务律师或者直接联系税务局。 美国的税务局挺亲民的, 您可以随时给他们打电话,去信或发电子邮件。联络办法如下:
http://www.irs.go /help/article/0,,id=96730,00.html 根据我的经验,税务局的客服做得不错,有函必复,回信及时。

要知道, 在一个民有民治民享的社会里 (A go ernment of the people, by the people and for the people), 税收确定了people 和 go ernment之间的从属关系。   一旦交了税, 您就可以以“纳税人”自居了。某种意义上, 你就是这个国家的主人了。 身为纳税人的您,有权利要求美国总统和国会向你报告, 为你的每一个dollar负责。

移民们,抓紧时间报税吧! 报税以后,您就可以给奥巴马写信劝他从伊拉克撤兵,敦促他别浪费你们这些纳税人的钱了。

————————————————-陳聰胤會計師———————————————————————

稅是無所不在的,人生除了生老病死必經過程之外,稅也是逃不掉的。住在米國不論你是否為米國公民,若有收入就必須報稅。在米國上班是雙週薪制的,每兩週領一次薪水,聯邦稅,州稅,等都把你扣走了。每年4月15日之前,你必須就去年所得,做個總結報稅。報稅的結果是,多退少補。每年年初大概這個時候,你會收到公司寄來的W2 Form,就是提醒你報稅季節到了。以2006 年來講,若你單身,年所得不超過8450美金,你是免繳所得稅的。以留學生而言,若你有一點獎學金或打工的收入,且有小孩子的,即使你可能全年被扣的聯邦稅(Federal income tax withheld)不到一千元,你也可以退稅超過千元,簡直是一個社會福利。原來米國為了有小孩的低收入家庭,立了一個稅法叫Earned Income Credit (EIC),鼓勵大人出去工作,低收入家庭,除了扣稅可全數退回之外,還可獲得補助。
所得稅表格可以在圖書館及郵局免費拿。單身沒小孩的上班族只要用1040EZ form即可,有小孩的用1040A,自己有房子,每月付貸款的,就必須要填最複雜的1040表了。這些1040表只是總表,副表(Forms and Schedules)還有很多種。1040EZ最簡單,只需填1040EZ的人,不用花錢買報稅軟體,報稅軟體很多種,以Turbo Tax及Tax Cut較普遍。報稅軟體一套少則30元,一百多元的也有,一百多元的是給幫人報稅的人用的,一般人用30塊錢的就可以了,稅法每年改,所以軟體也要每年買。用報稅軟體報稅,填表不會比較快,尤其是如果你是第一次用。你要花不少時間學怎麼使用,但退稅會比較快。電子報稅(e-filing)是以後的趨勢,我們每天上網傳電子郵件,報稅還用手填郵寄,是蠻落後的。在這分工的社會也有會自己換車子機油的,但是報稅給人報,跟車子壞了給人修,是同樣的一個道理的。

两个1040NR-EZ填写例子:

tax_f1040nre_example

EZ-J1scholar

遙遠的呼喚(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.