2012/03/13

Array and JSON

0 comments
Convert array thành JSON string thì dễ quá, chắc ai cũng biết:

// Server side
Person[] people = {
    new Person(10001, "Khanh", "Dao"),
    new Person(10002, "Handsome", "Linh")
};

JavaScriptSerializer js = new JavaScriptSerializer();
string result = js.Serialize(people);

Kết quả:
[
    {"ID":1001,"FirstName":"Khanh","LastName":"Dao"},
    {"ID":1002,"FirstName":"Handsome","LastName":"Linh"}
]

Giả sử bạn dùng jQuery để parse chuỗi trên thành array, và muốn dùng javascript để tìm một object có ID = 1002 trong array đó:

// Client side
var people = jQuery.parseJSON($("selector").text());
var person;
for (int i...) {
    if (people[i].ID == 1002) {
        person = people[i];
    }
}

Cái đám for ... if kia nhìn thật là chán! Đấy không phải là cách làm với JSON!
Nhưng đấy chỉ là khai vị.
Bây giờ mới vào món chính:

Trước khi serialize, convert array thành dictionary. Như vậy, mỗi object sẽ có ID:

// Server side
Person[] people = {
    new Person(10001, "Khanh", "Dao"),
    new Person(10002, "Handsome", "Linh")
};

JavaScriptSerializer js = new JavaScriptSerializer();
string result = js.Serialize(people.ToDictionary(item => item.ID.ToString(), item => item));

Kết quả:
{
    "1001":{"ID":1001,"FirstName":"Khanh","LastName":"Dao"},
    "1002":{"ID":1002,"FirstName":"Handsome","LastName":"Linh"}
}

và code javascript trở nên trong sáng lạ thường:

// Client side
var people = jQuery.parseJSON($("selector").text());
var person = people[1002];

Hint: Dùng thư viện Json.NET sẽ nhanh hơn, và đủ thông minh để chấp nhận int làm key cho dictionary :)

Happy coding!
2012/02/07

C# big file copy

0 comments
        public static void Copy(Stream input, string targetFile, int length)
        {
            byte[] buffer = new byte[8192];
            using (Stream output = File.OpenWrite(targetFile))
            {
                int bytesRead = 1;
                while (length > 0 && bytesRead > 0)
                {
                    bytesRead = input.Read(buffer, 0, Math.Min(length, buffer.Length));
                    output.Write(buffer, 0, bytesRead);
                    length -= bytesRead;
                }
            }
        }

        public static void CopyFile(string sourceFile, string targetFile)
        {
            if (File.Exists(targetFile))
            {
                File.Delete(targetFile);
            }
            Stream input = File.OpenRead(sourceFile);
            Copy(input, targetFile, (int)input.Length);
            System.GC.Collect();
        }

The old story but never out date

0 comments
The old story but never out date
2011/12/14

Using jQuery to select/deselect all

0 comments
Using jQuery to select/deselect all with just 3 lines of code

$("input[id$='selectAll']").click(function () { 
        $("INPUT[type='checkbox'][id*='chkbox']").attr("checked", $(this).is(":checked"));
});
 

Khanh DAO | © 2011

Design by DheTemplate.com and Theme 2 Blog