Showing posts with label coding. Show all posts
Showing posts with label coding. Show all posts
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();
        }
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"));
});
2011/12/13

SHA256 in SQL Server using CRL

2 comments
1. Create C# HashProc class, compile to HashProc.dll
using System;

public class HashProc
{
 [Microsoft.SqlServer.Server.SqlFunction(IsDeterministic = true, DataAccess = Microsoft.SqlServer.Server.DataAccessKind.None)]
 public static void SHA256(string inputStr, out string outputStr)
 {
  using (System.Security.Cryptography.SHA256Managed SHA256Crypto = new System.Security.Cryptography.SHA256Managed())
  {
   byte[] input = System.Text.Encoding.UTF8.GetBytes(inputStr);
   input = SHA256Crypto.ComputeHash(input);
   System.Text.StringBuilder output = new System.Text.StringBuilder();
   foreach (byte b in input)
   {
    output.Append(b.ToString("x2", System.Globalization.CultureInfo.InvariantCulture).ToUpperInvariant());
   }

   outputStr = output.ToString();
  }
 }
}

2. Enable CLR in SQL server
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'clr enabled', 1;
GO
RECONFIGURE;
GO

3. Register HashProc.dll into SQL server as a assembly
CREATE ASSEMBLY hashproc from 'C:\path\to\HashProc.dll' WITH PERMISSION_SET = SAFE;
GO

4. Create stored procedure to call the assembly hashproc
CREATE PROCEDURE sp_hash
@inputStr nvarchar(250),
@outputStr nvarchar(250) OUT
AS
EXTERNAL NAME hashproc.HashProc.SHA256;
GO

5. Call the stored procedure
DECLARE @outputStr nvarchar(250)
EXEC [dbo].[sp_hash]
  @inputStr = N'Test',
  @outputStr = @outputStr OUTPUT
SELECT @outputStr as N'@outputStr'
GO


Note: Confirm your SQL server CLR version supported using
select * from sys.dm_clr_properties;

That's all. You can change the HashProc class to using some more cryptography as SHA384 or SHA512 etc.
 

Khanh DAO | © 2011

Design by DheTemplate.com and Theme 2 Blog