2012-04-24

Multiplayer HTML5 game with Node

Tối nay lang thang 1 vòng coi có game engine gì hay không, nói chung vẫn chưa có gì mới nhiều.
Mình vẫn muốn và đang tìm để cùng vài người chế 1 game gì đó dạng 2D isometric MMORPG. Hy vọng sắp tới WebSocket sẽ OK hơn cũng như có nhiều engine phát triển hơn.

Thiệt ra bao giờ một mình mà đủ thời gian và resource làm được 1 cái như BrowserQuest http://browserquest.mozilla.org đã là kỳ công lắm rồi nhưng chẳng lẽ chỉ show off như Mozilla.

Muốn có thể làm được cái gì đó nhưng tự hiểu một mình ko đủ khả năng và quan trọng là không để làm gì. Hiện tại thì vẫn là "giấc mơ" ... :D.

2012-03-18

EventAggregator without Prism

Nếu trước đây vài năm, ai đã từng dùng EventBroker của CAB/SCSF và sau đó là EventAggregator của Prism thì không khó khăn gì nhận ra sự linh hoạt của nó so với cách viết thông thường. Tuy nhiên CAB/SCSF EventBroker khó tách ra thành 1 project, hơn nữa cách tiếp cận WorkItem và attribute có vẻ không hợp với các IoC container library sau này.

Dạo gần đây khi review 1 số dự án junior viết, mình nhận thấy code nhất là phần UI rất lộn xộn và không thể nào đọc được. Hầu như không junior nào có khái niệm phải thay đổi cách tổ chức. Nếu làm lại hết tất cả từ đầu thì không khả thi vì vậy mình tìm các apply 1 phần nhỏ để chỉnh lại đám UI code.

Tất nhiên EventAggregator của Prism theo mình nghĩ sẽ là source code hay nhất có thể dễ dàng modified và đưa vào project đã có. Nếu ai đã làm quen với Prism hay thậm chí chỉ cần biết qua về IoC contaienr library nào đó dễ thấy rằng việc đưa EventAggregator vào có thể dễ dàng dọn dẹp được rất nhiều code garbage. Đây là mô tả của Martin Flower http://martinfowler.com/eaaDev/EventAggregator.html.

OK xem thử code EventAggregator của Prism. Thực sự sau khi xem thì cũng không có nhiều việc phải chỉnh. Hơn nữa license của Prism cũng không cấm modified http://compositewpf.codeplex.com/license. Chỉ cần copy các files trong v4/PrismLibrary/Desktop/Prism/Events. Có 1 phần nhỏ để chỉnh lại là DefaultDispatcher.Desktop.cs. Class DefaultDispatcher dùng để marshal code trong trường hợp thread cần marshal đến là UI thread. Trước khi modify PL cũng search qua 1 số code trên Internet nhưng 1 số code lại comment luôn phần dispatcher trong trường hợp scope là UI. Tuy nhiên cũng không khó khăn gì nếu dùng SynchronizationContext như cách BackgroundWorker hay EventBroker của CAB.

Trong với WPF đơn giản code như sau:

if (Application.Current != null)
{
    Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, method, arg);
}

Nếu dùng code với console app hay WinForms thì cần thay bằng SynchronizationContext. Nếu muốn tìm hiểu SynchronizationContext là gì thì trên CodeProject có bài 2 phần giải thích về class này http://www.codeproject.com/Articles/31971/Understanding-SynchronizationContext-Part-I.

Code sau khi chỉnh như sau:

namespace Microsoft.Practices.Prism.Events
{
    /// Wraps the Application Dispatcher.

    public class DefaultDispatcher : IDispatcherFacade    {
        /// Forwards the BeginInvoke to the current application's .

        /// method Method to be invoked.
        /// arg Arguments to pass to the invoked method.
        public void BeginInvoke(Delegate method, object arg)
        {
#if WPF
            if (Application.Current != null)
            {
                Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, method, arg);
            }
#else

            if (SynchronizationContext.Current != null)
            {
                SynchronizationContext.Current.Send(data =>
                {
                    try
                    {
                        ((Delegate)data).DynamicInvoke(arg);
                    }
                    catch (TargetInvocationException ex)
                    {
                        Debug.WriteLine("There is an exception when marshal to UI thread: " + ex.Message);
                    }
                }, method);
            }
            else
            {
                try
                {
                    method.DynamicInvoke(arg);
                }
                catch (TargetInvocationException ex)
                {
                    Debug.WriteLine("There is an exception when marshal to UI thread: " + ex.Message);
                }
            }
#endif
        }
    }
}

2012-03-05

Flex/Flash - Security sandbox violation

Error #2010: Local-with-filesystem SWF files are not permitted to use sockets.
Add this configuration setting -use-network=false
http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html

2012-02-29

Sh#rp-Lite: error 'At least one ISessionFactory has not been registered with IoC'

Hôm nay ngồi coi lại Sharp-Lite chút, bữa có download về nhưng chỉ xem qua. Lần này mình tính evaluate xem có hợp lý hơn cái framework đang xài hay có gì hay hơn  so với S#arp Architecture không.

Lần đầu build không sao, lần sau copy mấy thứ từ project cũ qua, thay StructureMap bằng Windsor tự nhiên gặp lỗi nhảm shit 'At least one ISessionFactory has not been registered with IoC'. Trong khi debug rõ ràng đã register rồi và code cũng chẳng đổi gì để đến nỗi sai. Search 1 vòng trên NET chỉ có 1 chỗ
Google Groups › S#arp Lite › Error while running the sample application. Mới kiểm tra lại, thiệt bó tay Init project reference MVC 4 'C:\Program Files\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies\System.Web.Mvc.dll', Web project reference MVC 3 'C:\Program Files\Microsoft ASP.NET\ASP.NET MVC 3\Assemblies\System.Web.Mvc.dll'.

>>> bị lỗi reference tới 2 assembly khác nhau

2012-02-14

Multiple output files from a T4 template

Lâu ngày ngồi modify lại T4 template của Subsonic. Thật ra là mình dùng cái template đó rồi modify lại để generate DTO, chứ không dùng Subsonic.

Nhìn thấy rối quá, thật ra lúc trước lười search. Search ra multiple output file solution của Damien Guard ở đây Multiple outputs from T4 made easy.
Latest source available at GitHub
Giờ thì sẽ chỉnh lại những template đang có.

Note: file T4 bắt buộc sinh ra ít nhất 1 file, vì vậy thay vì output extension là .cs thì chuyển thành .log và ghi những thông tin cần thiết vào đây, ví dụ ngày giờ generated ... Ví dụ như sau:


// -----------------------------------------------------------------------------
//   GENERATED AT <#= DateTime.Now.ToShortDateString() + ", " + DateTime.Now.ToLongTimeString() #>
// -----------------------------------------------------------------------------
<#@ template language="C#" debug="False" hostspecific="True"  #>
<#@ include file="SQLServer.ttinclude" #>
<#@ include file="Manager.ttinclude"#>
<#@ output extension=".log" #>

2012-02-06

Windows 7 : add Command Prompt in right click context menu

Original: http://www.blogsdna.com/2226/windows-7-add-elevated-command-prompt-option-in-right-click-context-menu.htm

cmd2folder.reg, right click on file -> Merge


Windows Registry Editor Version 5.00


[HKEY_CLASSES_ROOT\Directory\shell\runas]
@="Command Line (Administrator)"


[HKEY_CLASSES_ROOT\Directory\shell\runas\command]
@="cmd.exe /s /k pushd \"%V\""

2011-11-01

Create self-signed certificate for localhost/DEV web server (enabled https/ssl)



Purposes

Để enabled SSL dùng trong flow xAuth, https://api.xxxyyy.vn/v1/oauth/access_token. Tạo môi trường test tại localhost hay server dev.

Download OpenSSL binary

1.       Download OpenSSL binary http://gnuwin32.sourceforge.net/packages/openssl.htm, bản mới nhất hiện tại là openssl-0.9.8h, extract phần bin (folder bin có chức các file exe như openssl.exe) vào folder giả sử D:\ openssl-0.9.8h.

2.       Tạo folder tương ứng certs, config, keys, p12, requests. Có thể chỉ dùng 1 folder cũng được

3.       Tạo file text database.txt, command tương ứng là

D:\openssl-0.9.8h>copy con database.txt
^Z

4.       Tạo file text serial.txt, nội dung có 1 dòng là 01

D:\openssl-0.9.8h>copy con serial.txt
01
^Z

5.       Download file config openssl.cnf, search trên Google là có liền (http://stuff.mit.edu/afs/athena/contrib/crypto/openssl.cnf hoặc copy từ thư mục Apache config của Wamp Server D:/Wamp/bin/apache/Apache2.2.17/conf) và copy vào folder config. Chỉnh lại các giá trị trong file config cho phù hợp: ví dụ dưới dùng dir = thư mục hiện tại (dấu .)

dir            = .
certs = $dir/certs
database = $dir/database.txt
new_certs_dir = $dir/certs
serial = $dir/serial.txt
...

6.       Bắt đầu dùng command line thực hiện các bước mô tả bên dưới, phần đường dẫn D:\ openssl-0.9.8h> trong các command bỏ qua.

Create CA key, self-signed CA cert

1.       Tạo CA key, command này sẽ yêu cầu một password

openssl genrsa -des3 -out keys\ca-key.pem 1024

2.       Tạo CA self-signed, output vào folder certs, valid 10 năm, dùng config file trong folder config đã chuẩn bị, phần Your Name ví dụ là company.com
openssl req -config config\openssl.cnf -new -x509 -days 3650 -key keys\ca-key.pem -out certs\ca-cert.cer

Backup/Remove passphrase from key

1.       Backup CA key

copy keys\ca-key.pem keys\ca-key-org.pem

2.       Tạo RSA private key

openssl rsa -in keys\ca-key-org.pem -out keys\ca-key.pem

Tới đây đã có CA cert và CA key

Create localhost (web server) private key (optional)

1.       Tương tự tạo private key cho web server (ở đây gọi là localhost hay xxxyyy) giả sử password là password localhost.key.

openssl genrsa -des3 -out keys\server-key.pem 1024

2.       Backup CA key

copy keys\server-key.pem  keys\server-key-org.pem

3.       Tạo RSA private key

openssl rsa -in keys\server-key-org.pem -out keys\server-key.pem

Bước này không cần thiết, vì trong bước sau sẽ thực hiện tạo Certificate Signing Request cùng với Private Key.

Create CSR + Private key

Tạo csr kết quả sẽ output trong folder requests, đồng thời tạo private key cho web server, phần Your Name nên để là localhost, tức địa chỉ localhost hay nếu dùng địa chỉ khác thì là www.company.com
openssl req -new -nodes  -days 3650 -config config\openssl.cnf -out requests\server-request.csr -keyout keys\server-key.pem

Sign request WITH CA key

Dùng command openssl ca để ký lên yêu cầu vừa mới tạo trong bước trước

openssl ca -policy policy_anything -config config\openssl.cnf -cert certs\ca-cert.cer -in requests\server-request.csr -keyfile keys\ca-key.pem -days 3650 -out certs\server-cert.cer

Create DER/p12

1.       Tạo DER format cer bằng command

openssl x509 -in certs\ca-cert.cer -outform DER -out certs\ca-cert.der

2.       Tạo p12 bằng command

openssl pkcs12 -export -in certs\ca-cert.cer -inkey keys\ca-key.pem -certfile certs\ca-cert.cer -out p12\ca.p12

Install CA as Trusted Root CA

Double click vào CA cert và install vào Trusted Root Certification Authorities store.

Install Cert with Wampserver

1.       Enable SSL trong file config của Apache, uncomment load module SSL và include HTTPS config

D:\Wamp\bin\apache\Apache2.2.17\conf\httpd.conf

LoadModule ssl_module modules/mod_ssl.so

Include conf/extra/httpd-ssl.conf

2.       Copy cert và private key của localhost vừa tạo vào folder config của WampServer Apache D:/Wamp/bin/apache/Apache2.2.17/conf
3.       Replace đường dẫn sai trong extra/httpd-ssl.conf dạng path-to-Apache-folder đang bị sai thường là c:/Apache2 thành D:/Wamp/bin/apache/Apache2.2.17 (tùy version và path đang dùng)
4.       Uncomment và chỉnh các giá trị SSLCertificateFile và SSLCertificateKeyFile

SSLCertificateFile "D:/Wamp/bin/apache/Apache2.2.17/conf/server-cert.cer"
SSLCertificateKeyFile "D:/Wamp/bin/apache/Apache2.2.17/conf/server-key.pem"

5.       Chỉnh lại đường đẫn enable SSL, có thể enable cả www của Wamp Server trong httpd-ssl.conf

DocumentRoot "D:/Wamp/www"
ServerName localhost:443

Testing

Nếu không start được wampapache. Có thể bị lỗi sau (xem trong event logs) có thể cần load thêm module mod_socache_shmcb 


The Apache service named  reported the following error:
>>> SSLSessionCache: 'shmcb' session cache not supported (known names: ). Maybe you need to load the appropriate socache module (mod_socache_shmcb?).     .