2011年12月27日 星期二

[筆記]Javascript Patterns 一些好習慣 -- for loops

for Loops

1: // sub-optimal loop

   2: for (var i = 0; i < myarray.length; i++) {
   3:     // do something with myarray[i]
   4: }
   5:  
   6: //應使用下面的寫法
   7: for (var i = 0, max = myarray.length; i < max; i++) {
   8:     // do something with myarray[i]
   9: }

如果要套上剛剛所說的 single var 的寫法的話



   1: function looper() {
   2:     var i = 0,
   3:         max,
   4:         myarray = [];
   5:     // ...
   6:     for (i = 0, max = myarray.length; i < max; i++) {
   7:         // do something with myarray[i]
   8:     }
   9: }

還可以更簡單嗎?? 下面只用到兩個變數



   1: function foo(){
   2:     var myarray = [],
   3:         i = myarray.length;
   4:     while(i--){
   5:         // do something with myarray[i]
   6:     }
   7: }


for-in Loops



for-in loops 大部份是用在不是 array 的物件身上,雖然也可以用在 Array 上,但並不建議。


在使用上可以用 hasOwnProperty(i) 來過濾物件屬性。如下面的  code 該物件有一個 clone() 的 function,就可以用 hasOwnProperty 來將其濾除



   1: // the object
   2: var man = {
   3:     hands: 2,
   4:     legs: 2,
   5:     heads: 1
   6: };
   7: // somewhere else in the code
   8: // a method was added to all objects
   9: if (typeof  Object.prototype.clone === "undefined") {
  10:     Object.prototype.clone = function () {};
  11: }
  12:  
  13: // 1.
  14: // for-in loop
  15: for (var i in man) {
  16:     if (man.hasOwnProperty(i)) { // filter
  17:         console.log(i, ":", man[i]);
  18:     }
  19: }
  20: /*
  21: result in the console
  22: hands : 2
  23: legs : 2
  24: heads : 1
  25: */
  26: // 2.
  27: // antipattern:
  28: // for-in loop without checking hasOwnProperty()
  29: for (var i in man) {
  30:     console.log(i, ":", man[i]);
  31: }
  32: /*
  33: result in the console
  34: hands : 2
  35: legs : 2
  36: heads : 1
  37: clone: function()
  38: */

 

不要用 eval()


這個應該不用多說, eval 會有潛在的安全性問題。


parseInt() 的注意事項


如果使用者輸入日期格式的文字在要 parseInt 的值時,在 舊版本的 javascript 會將該文字當作 8 進位來計算,會造成錯誤。所以在用 parseInt 時要指定 radix 的值



   1: var month = "06",
   2:     year = "09";
   3: month = parseInt(month, 10);
   4: year = parseInt(year, 10);

在大多數的狀況下也可以用下面的方式



   1: +"08" // result is 8
   2: Number("08") // 8

雖然速度會比較快一點,不過因為 parseInt 還做了 parse 的動作,所以像 “08 hello” 這樣子的文字還是可以正常的 parse 出來,而 用上面方法的就只會回傳 NaN 了

[筆記]Javascript Patterns 一些好習慣–Global 變數

JSLint

用 JSLint 來測定你的 javascript 的品質。

The Console

Console 物件並不是 javascript 的一部份,而是屬於 Browser。

Console 物件可以用來 取代 alert()。與其將變數的值alert出來,不如就用 console.log 將值顯示出來吧。(alert 會中斷程式執行)

 

寫 Javascript 的好習慣

Minimizing Globals

javascript 是利用 function 來定義命名空間(scope)。在function 裡定義的變數是 local 變數,在function之外則存取不到。而 global 變數則是存在 function 之外,每一個 global 變數會變成一個global 物件的屬性(property)

   1: myglobal = "hello"; // antipattern
   2: console.log(myglobal); // "hello"
   3: console.log(window.myglobal); // "hello"
   4: console.log(window["myglobal"]); // "hello"
   5: console.log(this.myglobal); // "hello"

使用 global 變數的問題



很容易跟其他人寫的 javascript 發生衝突,而此種衝突是最難發現的,有人在 global 定義了一個變數叫 result 則以下的 code 就會將 result 的值改變,造成潛在的  bug




   1: function sum(x, y) {
   2:     // antipattern: implied global
   3:     result = x + y;
   4:     return result;
   5: }
var 讓 result 這個變數變成 local ,就不會造成  global 的問題



   1: function sum(x, y) {
   2:     // antipattern: implied global
   3:     var result = x + y;
   4:     return result;
   5: }

小心這樣也會變成 global



chain assignments



   1: function foo() {

   2:     // antipattern: do not use
   3:     var a = b = 0;
   4:     // ….
   5: }


上面的 code 等同於 var a = (b = 0);  不小心就多了一個 global 變數,應該改為下面的寫法。




       1: function foo() {
       2:     var a, b;
       3:     // ...
       4:     a = b = 0; // both local
       5: }


如何安全的使用 Global



如果真的必需要使用 global 也請用下面的方式來寫,以提醒自已目前使用的是 global 變數



   1: var global = (function(){return this;}());
   2:  
   3: test1();
   4:  
   5: function test1(){
   6:   global.msg = "this is test 1";
   7:   test2();
   8: }
   9: function test2(){
  10:   console.log(global.msg);
  11:   console.log("msg:" + msg);
  12: }

使用單一 var 來定義變數 (single var)



好處



  • 將所有的變數定義在程式最開始的地方
  • 避免使用到未定義的變數
  • 幫助你記得要定義變數,以避免不小心將變數變成 global
  • 較少的程式碼


   1: function func() {
   2:     var a = 1,
   3:         b = 2,
   4:         sum = a + b,
   5:         myobject = {},
   6:         i,
   7:         j;
   8:     // function body...
   9: }
  10:  
  11: function updateElement() {
  12:     var el = document.getElementById("result"),
  13:         style = el.style;
  14:     // do something with el and style...
  15: }

2011年12月22日 星期四

All-in-One Code Framework 很多 Code Sample 的地方

一直覺得學東西最快的方式就是看人家寫的 sample。Microsoft 推出了這個站 All-in-One Code Framework. 提供了許多的 sample 。而且如果沒有你想要的範例,你還可以提出需求,讓 Microsoft 的工程師幫你寫一個喲。

參考連結:

http://1code.codeplex.com/

2011年12月21日 星期三

Entity Framework with Unity IoC

在使用 EF4.1 及 Unity 時遇到了資料更新後還會取得舊資料的問題。發現原來是因為使用了 Unity 的關係。

Unity 記下了DBContext 的Instance 而不會在每次 request 的時後重新建立。所以會產生取得舊資料的問題。要記得加上 HierarchicalLifetimeManager 才能夠讓 dbContext  在每次 Request 的時後重建。

   1: private static IUnityContainer BuildUnityContainer()
   2: {
   3:     var container = new UnityContainer();
   4:  
   5:     container.RegisterType<ILtsService, LtsService>();
   6:     container.RegisterType<IEmpService, EmpService>();
   7:  
   8:     container.RegisterType<WEKIDSDBEntities>(new HierarchicalLifetimeManager());
   9:     container.RegisterType<CodeGroupHelper>(new PerThreadLifetimeManager());
  10:     container.RegisterType<SeqNoHelper>(new PerThreadLifetimeManager());
  11:     
  12:     container.RegisterInstance<IUnityContainer>(container, new PerThreadLifetimeManager());
  13:     
  14:     container.RegisterControllers();
  15:  
  16:     return container;
  17: }

 


參考資料:


Introducing The Unity.Mvc3 NuGet Package To Reconcile MVC3, Unity and IDisposable

2010年11月15日 星期一

New Delphi language features since Delphi 7

由 http://edn.embarcadero.com/article/34324 轉 post 過來

 

Abstract: See many of the major new language features in Delphi released after the Delphi 7 version

Language and Compiler Features Since Delphi 7

Inlining
Routines can now be marked with the inline directive.  This tells the compiler that, instead of actually calling the routine, it should emit code that includes the routine at the call site.

Operator Overloading

Delphi allows certain functions, or operators, to be overloaded within record declarations

TMyClass = class
class operator Add(a, b: TMyClass): TMyClass; // Addition of two operands of type TMyClass
class operator Subtract(a, b: TMyClass): TMyclass; // Subtraction of type TMyClass
class operator Implicit(a: Integer): TMyClass; // Implicit conversion of an Integer to type TMyClass
class operator Implicit(a: TMyClass): Integer; // Implicit conversion of TMyClass to Integer
class operator Explicit(a: Double): TMyClass; // Explicit conversion of a Double to TMyClass
end;

// Example implementation of Add class operator
TMyClass.Add(a, b: TMyClass): TMyClass;
begin
...
end;

var
x, y: TMyClassbegin
x := 12; // Implicit conversion from an Integer
y := x + x; // Calls TMyClass.Add(a, b: TMyClass): TMyClass
b := b + 100; // Calls TMyClass.Add(b, TMyClass.Implicit(100))
end;


Class Helpers

A class helper is a type that - when associated with another class - introduces additional method names and properties which may be used in the context of the associated class (or its descendants). Class helpers are a way to extend a class without using inheritance. A class helper simply introduces a wider scope for the compiler to use when resolving identifiers. When you declare a class helper, you state the helper name, and the name of the class you are going to extend with the helper. You can use the class helper any place where you can legally use the extended class. The compiler's resolution scope then becomes the original class, plus the class helper. Class helpers provide a way to extend a class, but they should not be viewed as a design tool to be used when developing new code. They should be used solely for their intended purpose, which is language and platform RTL binding.

type
TMyClass = class

procedure MyProc;
function MyFunc: Integer;
end;

...

procedure TMyClass.MyProc;
var
X: Integer;
begin
X := MyFunc;
end;

function TMyClass.MyFunc: Integer;
begin
...
end;

...

type
TMyClassHelper = class helper for TMyClass
procedure HelloWorld;
function MyFunc: Integer;
end;

...

procedure TMyClassHelper.HelloWorld;
begin
WriteLn(Self.ClassName); // Self refers to TMyClass type, not TMyClassHelper

end;

function TMyClassHelper.MyFunc: Integer;
begin
...
end;
...

var
X: TMyClass;
begin
X := TMyClass.Create;
X.MyProc; // Calls TMyClass.MyProc
X.HelloWorld; // Calls TMyClassHelper.HelloWorld
X.MyFunc; // Calls TMyClassHelper.MyFunc

end;

strict private
The private keyword actually creates a " friendship" relationship between classes in the same unit.  The strict private declaration creates a true private field, not viewable by any other class, not even classes in the same unit.

strict protected
Similar to the strict private declaration, strict protectedcreates a true protected member, visible only to the declaring class and its descendents.

Records with Methods

In addition to fields, records now may have properties and methods (including constructors), class properties, class methods, class fields, and nested types.

type
TMyRecord = record
type
TInnerColorType = Integer;
var
Red: Integer;
class var
Blue: Integer;
procedure printRed();
constructor Create(val: Integer);
property RedProperty: TInnerColorType read Red write Red;
class property BlueProp: TInnerColorType read Blue write Blue;
end;

constructor TMyRecord.Create(val: Integer);
begin
Red := val;
end;

procedure TMyRecord.printRed;
begin
writeln('Red: ', Red);
end;

class abstract

Classes, and not just methods, can be declared as abstract.

type
TAbstractClass = class abstract
procedure SomeProcedure;
end;

class sealed
Classes marked as sealed cannot be inherited from.

type
TAbstractClass = class sealed
procedure SomeProcedure;
end;

class const
Classes can now have class constants -- a constant value associated with the class itself and not an instance of the class.

type
TClassWithConstant = class
public
const SomeConst = 'This is a class constant';
end;


procedure TForm1.FormCreate(Sender: TObject);
begin
ShowMessage(TClassWithConstant.SomeConst);
end;

class type
A class can now contain a type declaration that is usable only within that class.

type
TClassWithClassType = class
private
type
TRecordWithinAClass = record
SomeField: string;
end;
public

class var
RecordWithinAClass: TRecordWithinAClass;
end;
...
procedure TForm1.FormCreate(Sender: TObject);
begin
TClassWithClassType.RecordWithinAClass.SomeField := 'This is a field of a class type declaration';
ShowMessage(TClassWithClassType.RecordWithinAClass.SomeField);
end;


class var
A class can also have a class variable, applicable only to the class and not an instance of the class. See "class type" for an example.

class property
A class can have a class property, which is a property that applies only to the class reference and not to an instance of a class.  The accessors for the class property must be either class methods or class variables. See the example in "static class methods" below.

nested classes
Type declarations can be nested within class declarations. They present a way to keep conceptually related types together, and to avoid name collisions.

type
TOuterClass = class
strict private
MyField: Integer;
public
type
TInnerClass = class
public
MyInnerField: Integer;
procedure InnerProc;
end;
procedure OuterProc;
end;

procedure TOuterClass.TInnerClass.InnerProc;
begin
...
end;

final methods
A virtual method that you override can now be marked final, preventing derived classes from overriding that method.

TAbstractClass = classabstract
public
procedure Bar; virtual;
end;

TSealedClass = classsealed(TAbstractClass)
public
procedure Bar; override;
end;

TFinalMethodClass = class(TAbstractClass)
public
procedure Bar; override; final;
end;

sealed methods
Classes marked as sealed cannot be descended from. See the example in 'final methods'.

static class methods
Classes can have static class methods -- i.e. methods that can be called from a class type. Class static methods can be accessed without an object reference. Unlike ordinary class methods, class static methods have no Self parameter at all. They also cannot access any instance members. (They still have access to class fields, class properties, and class methods.) Also unlike class methods, class static methods cannot be declared virtual.

type
TMyClass = class
strict private
class var
FX: Integer;
strict protected

// Note: accessors for class properties must be declared class static.

class function GetX: Integer; static;
class procedure SetX(val: Integer); static;
public
class property X: Integer read GetX write SetX;
class procedure StatProc(s: String); static;
end;

TMyClass.X := 17;
TMyClass.StatProc('Hello');

for-in loop
Delphi 2007 for Win32 supports for-element-in-collection style iteration over containers. The following container iteration patterns are recognized by the compiler:

  for Element in ArrayExpr do Stmt;
for Element in StringExpr do Stmt;
for Element in SetExpr do Stmt;
for Element in CollectionExpr do Stmt;

LATEST COMMENTS

2010年10月5日 星期二

Learning Plan for Microsoft .NET Framework 4.0, Web Applications Development (Exam 70-515) Step 1

 

Choosing the Right Programming Model

What does ASP.NET WebForms value?

  • Familiar control and event-base programming model
  • Controls encapsulate HTML, JS and CSS
  • Rich UI controls included - datagirds, charts, AJAX
  • Browser differences handled for you
  • SharePoint Builds on WebForms

What does ASP.NET MVC value?

  • Feels comfortable for many traditional web developers
  • Total control of HTML markup
  • Supports Unit Testing, TDD and Agile methodologies
  • Encourage more prescriptive applications
  • Extremly flexible and extensible

ASP.NET WebForms and ASP.net MVC 是可以在一個網站內共存的

2010年6月14日 星期一

TortoiseSVN 常用指令介紹 Part 3.

上一篇介紹的是每天開工時需做的動作

這一篇要介紹的是工作中常會用到的指令

新增, 刪除, 複製, 移動

  • svn add

  • svn delete

  • svn copy

  • svn move

難免會有做錯的時後,這是類似 VSS 中 Undo CheckOut 的功能

  • svn Revert

當你的工作告一段落時,你要將你所做的修改 Commit 提交至SVN當中

  • svn commit

最後,當在操作 SVN 發生操作中斷

  • svn cleanup

 

 

SVN Add, Delete, Copy, Move

svn add 在第一篇時已經有提到過了,基本上就是將新的檔案加入 SVN 當中。那我們在這裡就不再提了

svn delete 刪除有兩個方式,一個是直接立用 檔案總管的功能將檔案刪除,但在 Commit 時會出現 Missing 的狀態,此時將該檔案勾選後再按下 OK 便可以將檔案除 SVN 中刪除。

image

另一個方式是以menu的方式選擇  TortoiseSVN –> delete 將檔案刪除。

image

刪除後記得要再將變更Commit進SVN當中。如此便可完成變更。

 

至於Copy, Move 呢?? 這也是滿簡單的。請在你要 Copy 或是 Move  的檔案以右鍵的方式拖拉到你想去的位置

image

他會跳出選單來讓你選擇,記得、變更完畢後要 Commit進SVN中。

 

SVN Revert

這個指令主要用意是將你對這個板本的修改做一個回復,但只限制未 Commit 的部份。

比如我們剛剛修改了檔案,卻發現改錯了。那就可以直接用 Revert 的這個指令

TortoiseSVN –> Revert 來將修改回復。但也要小心使用,要不然可能將你剛剛的心血一不小心就給他白費了。

image

image

將要回復的檔案勾選,按下 OK 便可。

 

SVN Commit

Commit 是將修改過後的變更提交至 SVN的功能。包括之前所提到的所有功能都需要用 Commit 來將變更提交至SVN。

image

在 Commit 時也可能會發生兩種狀況。

  1. 修改的期間沒有新的版本變動
  2. 修改期間有新的版本變動 –> 需手動作 Merge 的動作 (Merge 在Part2大約有提到過了)

狀況 1 當然是最佳的情境,基本上按下  commit 後就會顯示出成功的結果了

image

但如果遇到有衝突的時後會出現以下的畫面。此時就必需要先做過 Update 的動作了。

image

 

SVN CleanUp

當 SVN 改變我們的工作拷貝時,有可能會發生 操作中斷、網路斷線、斷電、電腦當機。此時只需要執行 Cleanup 就可以將未完成的功作完成。

image

 

 

最後再回顧一下今天用到的指令

新增, 刪除, 複製, 移動

  • svn add

  • svn delete

  • svn copy

  • svn move

 

  • svn Revert

 

  • svn commit
  • svn cleanup